<template>
  <div class="diet-container">
    <div class="page-header">
      <h1>饮食分析与建议</h1>
      <p class="sub-title">记录您的饮食习惯，获取专业的营养建议</p>
    </div>

    <!-- 时间范围选择器 -->
    <div class="time-range-selector">
      <el-radio-group v-model="timeRange" @change="changeTimeRange">
        <el-radio-button label="day">今日</el-radio-button>
        <el-radio-button label="week">近七天</el-radio-button>
        <el-radio-button label="month">本月</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 饮食记录区域 -->
    <div class="diet-record-area" v-if="timeRange === 'day'">
      <el-card class="meal-card" v-loading="isLoading" element-loading-text="加载中...">
        <div slot="header" class="meal-header">
          <div class="header-left">
          <span>今日饮食记录</span>
            <span class="header-date">{{ displayDate }}</span>
          </div>
          <div class="header-right">
            <el-button type="text" icon="el-icon-refresh" @click="refreshData" :disabled="isLoading">刷新</el-button>
          </div>
        </div>
        
        <el-alert
          title="提示：您可以记录今日饮食并保存，以便后续查看分析报告"
          type="info"
          :closable="false"
          show-icon
          class="save-tip">
        </el-alert>
        
        <!-- 添加餐次的按钮 -->
        <div class="add-meal-btn" @click="addMeal">
          <i class="el-icon-plus"></i>
          <span>添加餐次</span>
        </div>

        <!-- 餐次列表 -->
        <div v-for="(meal, mealIndex) in meals" :key="mealIndex" class="meal-item" :class="{'saved-meal': meal.isSaved}">
          <div class="meal-item-header">
            <el-select v-model="meal.type" placeholder="选择餐次" class="meal-type-select" :disabled="meal.isSaved">
              <el-option v-for="item in mealTypes" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
            <el-time-picker
              v-model="meal.time"
              format="HH:mm"
              placeholder="用餐时间"
              class="meal-time-picker"
              :disabled="meal.isSaved">
            </el-time-picker>
            <el-tag v-if="meal.isSaved" type="success" size="small" class="saved-tag">已保存</el-tag>
            <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="removeMeal(mealIndex)" class="delete-meal-btn"></el-button>
          </div>

          <!-- 食材列表 -->
          <div class="food-items-container">
            <div v-for="(food, foodIndex) in meal.foods" :key="foodIndex" class="food-item">
              <el-select
                v-model="food.category"
                placeholder="食材类别"
                @change="onFoodCategoryChange(mealIndex, foodIndex)"
                class="food-category"
                :disabled="meal.isSaved">
                <el-option
                  v-for="category in foodCategories"
                  :key="category.value"
                  :label="category.label"
                  :value="category.value">
                </el-option>
              </el-select>

              <el-select
                v-model="food.name"
                filterable
                placeholder="选择或输入食材"
                class="food-name"
                :disabled="!food.category || meal.isSaved">
                <el-option
                  v-for="item in getFoodOptions(food.category)"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>

              <el-input-number 
                v-model="food.amount" 
                :min="1" 
                :max="1000" 
                size="small" 
                class="food-amount"
                :disabled="!food.name || meal.isSaved">
              </el-input-number>
              
              <span class="unit-label">克</span>
              
              <el-button 
                type="danger" 
                icon="el-icon-close" 
                circle 
                size="mini" 
                @click="removeFood(mealIndex, foodIndex)"
                class="delete-food-btn"
                :disabled="meal.isSaved"
                :title="meal.isSaved ? '已保存的餐次不能删除单个食材' : '删除食材'">
              </el-button>
            </div>

            <!-- 添加食材按钮 -->
            <div class="add-food-btn" @click="addFood(mealIndex)" v-if="!meal.isSaved">
              <i class="el-icon-plus"></i>
              <span>添加食材</span>
            </div>
            
            <!-- 已保存餐次提示 -->
            <div class="saved-meal-tip" v-if="meal.isSaved">
              <i class="el-icon-info"></i>
              <span>已保存的餐次不能修改或删除单个食材，如需修改请删除整个餐次后重新添加</span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 分析和建议按钮 -->
      <div class="action-btns">
        <el-button type="primary" @click="analyzeDiet" :disabled="!canAnalyze || isLoading">分析饮食结构</el-button>
        <el-button type="success" @click="saveMealRecord" :disabled="!canAnalyze || isLoading">保存饮食记录</el-button>
        <el-button type="warning" @click="showDailyAdvice" :disabled="isLoading">获取专业建议</el-button>
        <el-button @click="resetForm" :disabled="isLoading">重置</el-button>
      </div>
    </div>

    <!-- 周视图 -->
    <div class="weekly-view" v-if="timeRange === 'week'">
      <el-card class="analysis-card" v-loading="isLoading" element-loading-text="加载中...">
        <div slot="header" class="meal-header">
          <span>近七天饮食总结</span>
          <span class="header-date">{{ weeklyDateRange }}</span>
        </div>
        
        <div class="weekly-summary">
          <div class="weekly-stats">
            <div class="stat-item">
              <div class="stat-value">{{ weeklyData.totalMeals || 0 }}</div>
              <div class="stat-label">用餐次数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ weeklyData.averageCalories.toFixed(0) || 0 }}</div>
              <div class="stat-label">平均热量(千卡/天)</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ weeklyData.totalCalories.toFixed(0) || 0 }}</div>
              <div class="stat-label">总热量(千卡)</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ weeklyData.vegetableMeals || 0 }}</div>
              <div class="stat-label">蔬果餐次</div>
            </div>
          </div>
          
          <!-- 餐次分布 -->
          <div class="meal-distribution">
            <h3>餐次分布</h3>
            <div class="meal-distribution-chart">
              <div class="meal-type-item">
                <div class="meal-type-bar" :style="{height: `${(weeklyData.breakfastCount / weeklyData.totalMeals * 100) || 0}%`}"></div>
                <div class="meal-type-label">早餐</div>
                <div class="meal-type-count">{{ weeklyData.breakfastCount || 0 }}</div>
              </div>
              <div class="meal-type-item">
                <div class="meal-type-bar" :style="{height: `${(weeklyData.lunchCount / weeklyData.totalMeals * 100) || 0}%`}"></div>
                <div class="meal-type-label">午餐</div>
                <div class="meal-type-count">{{ weeklyData.lunchCount || 0 }}</div>
              </div>
              <div class="meal-type-item">
                <div class="meal-type-bar" :style="{height: `${(weeklyData.dinnerCount / weeklyData.totalMeals * 100) || 0}%`}"></div>
                <div class="meal-type-label">晚餐</div>
                <div class="meal-type-count">{{ weeklyData.dinnerCount || 0 }}</div>
              </div>
              <div class="meal-type-item">
                <div class="meal-type-bar" :style="{height: `${(weeklyData.snackMorningCount / weeklyData.totalMeals * 100) || 0}%`}"></div>
                <div class="meal-type-label">上午加餐</div>
                <div class="meal-type-count">{{ weeklyData.snackMorningCount || 0 }}</div>
              </div>
              <div class="meal-type-item">
                <div class="meal-type-bar" :style="{height: `${(weeklyData.snackAfternoonCount / weeklyData.totalMeals * 100) || 0}%`}"></div>
                <div class="meal-type-label">下午加餐</div>
                <div class="meal-type-count">{{ weeklyData.snackAfternoonCount || 0 }}</div>
              </div>
              <div class="meal-type-item">
                <div class="meal-type-bar" :style="{height: `${(weeklyData.snackEveningCount / weeklyData.totalMeals * 100) || 0}%`}"></div>
                <div class="meal-type-label">夜宵</div>
                <div class="meal-type-count">{{ weeklyData.snackEveningCount || 0 }}</div>
              </div>
            </div>
          </div>
          
          <div class="weekly-nutrition-chart">
            <h3>周营养素摄入情况</h3>
            
            <!-- 营养素比例饼图 -->
            <div class="weekly-pie-chart">
              <div class="pie-chart-container">
                <div class="pie-chart">
                  <!-- 使用SVG绘制饼图 -->
                  <svg viewBox="0 0 100 100" class="pie-svg">
                    <!-- 碳水化合物扇区 -->
                    <path v-if="weeklyData.carbohydratePct > 0"
                      :d="calculatePieSegment(0, weeklyData.carbohydratePct)"
                      class="pie-segment carbs-segment" />
                    
                    <!-- 蛋白质扇区 -->
                    <path v-if="weeklyData.proteinPct > 0"
                      :d="calculatePieSegment(weeklyData.carbohydratePct, weeklyData.carbohydratePct + weeklyData.proteinPct)"
                      class="pie-segment protein-segment" />
                    
                    <!-- 脂肪扇区 -->
                    <path v-if="weeklyData.fatPct > 0"
                      :d="calculatePieSegment(weeklyData.carbohydratePct + weeklyData.proteinPct, weeklyData.carbohydratePct + weeklyData.proteinPct + weeklyData.fatPct)"
                      class="pie-segment fat-segment" />
                    
                    <!-- 膳食纤维扇区 -->
                    <path v-if="weeklyData.fiberPct > 0"
                      :d="calculatePieSegment(weeklyData.carbohydratePct + weeklyData.proteinPct + weeklyData.fatPct, 100)"
                      class="pie-segment fiber-segment" />
                    
                    <!-- 中心圆 -->
                    <circle cx="50" cy="50" r="30" class="pie-center" />
                  </svg>
                </div>
                
                <!-- 营养素图例 -->
                <div class="chart-legend">
                  <div class="legend-row">
                    <div class="legend-item">
                      <span class="color-box carbs-color"></span>
                      <span class="legend-text">
                        碳水化合物 {{ weeklyData.carbohydratePct.toFixed(1) }}%
                        <span class="grams-value">({{ weeklyData.totalCarbohydrate.toFixed(1) }}g)</span>
                      </span>
              </div>
                    <div class="legend-item">
                      <span class="color-box protein-color"></span>
                      <span class="legend-text">
                        蛋白质 {{ weeklyData.proteinPct.toFixed(1) }}%
                        <span class="grams-value">({{ weeklyData.totalProtein.toFixed(1) }}g)</span>
                      </span>
                    </div>
                  </div>
                  <div class="legend-row">
                    <div class="legend-item">
                      <span class="color-box fat-color"></span>
                      <span class="legend-text">
                        脂肪 {{ weeklyData.fatPct.toFixed(1) }}%
                        <span class="grams-value">({{ weeklyData.totalFat.toFixed(1) }}g)</span>
                      </span>
                    </div>
                    <div class="legend-item">
                      <span class="color-box fiber-color"></span>
                      <span class="legend-text">
                        膳食纤维 {{ weeklyData.fiberPct.toFixed(1) }}%
                        <span class="grams-value">({{ weeklyData.totalFiber.toFixed(1) }}g)</span>
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 周饮食建议 -->
        <div class="weekly-suggestions">
          <h3>本周饮食建议</h3>
          <div v-if="weeklyAdvice.loading" class="loading-advice">
            <i class="el-icon-loading"></i>
            <span>正在获取专业建议...</span>
          </div>
          <div v-else-if="weeklyAdvice.content" class="weekly-advice-content">
            <div class="formatted-advice" v-html="formatAdvice(weeklyAdvice.content)"></div>
          </div>
          <div v-else class="suggestion-list">
            <div class="suggestion-item" v-for="(suggestion, index) in weeklyData.suggestions" :key="index">
              <div class="suggestion-icon">
                <i :class="suggestion.icon"></i>
              </div>
              <div class="suggestion-text">
                <h4>{{ suggestion.title }}</h4>
                <p>{{ suggestion.content }}</p>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 月视图 -->
    <div class="monthly-view" v-if="timeRange === 'month'">
      <el-card class="analysis-card" v-loading="isLoading" element-loading-text="加载中...">
        <div slot="header" class="meal-header">
          <span>本月饮食总结</span>
          <span class="header-date">{{ monthlyDateRange }}</span>
        </div>
        
        <div class="monthly-summary">
          <div class="monthly-stats">
            <div class="stat-item">
              <div class="stat-value">{{ monthlyData.totalMeals || 0 }}</div>
              <div class="stat-label">总用餐次数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ monthlyData.breakfastCount || 0 }}</div>
              <div class="stat-label">早餐次数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ monthlyData.lunchCount || 0 }}</div>
              <div class="stat-label">午餐次数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ monthlyData.dinnerCount || 0 }}</div>
              <div class="stat-label">晚餐次数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ monthlyData.averageCalories.toFixed(0) || 0 }}</div>
              <div class="stat-label">平均热量(千卡/天)</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ monthlyData.vegetableMeals || 0 }}</div>
              <div class="stat-label">蔬果餐次</div>
            </div>
          </div>
          
          <div class="monthly-nutrition-chart">
            <h3>月度营养结构分析</h3>
            
            <!-- 营养素比例饼图 -->
            <div class="monthly-pie-chart">
              <div class="pie-chart-container">
                <div class="pie-chart">
                  <!-- 使用SVG绘制饼图 -->
                  <svg viewBox="0 0 100 100" class="pie-svg">
                    <!-- 碳水化合物扇区 -->
                    <path v-if="monthlyData.carbohydratePct > 0"
                      :d="calculatePieSegment(0, monthlyData.carbohydratePct)"
                      class="pie-segment carbs-segment" />
                    
                    <!-- 蛋白质扇区 -->
                    <path v-if="monthlyData.proteinPct > 0"
                      :d="calculatePieSegment(monthlyData.carbohydratePct, monthlyData.carbohydratePct + monthlyData.proteinPct)"
                      class="pie-segment protein-segment" />
                    
                    <!-- 脂肪扇区 -->
                    <path v-if="monthlyData.fatPct > 0"
                      :d="calculatePieSegment(monthlyData.carbohydratePct + monthlyData.proteinPct, monthlyData.carbohydratePct + monthlyData.proteinPct + monthlyData.fatPct)"
                      class="pie-segment fat-segment" />
                    
                    <!-- 膳食纤维扇区 -->
                    <path v-if="monthlyData.fiberPct > 0"
                      :d="calculatePieSegment(monthlyData.carbohydratePct + monthlyData.proteinPct + monthlyData.fatPct, 100)"
                      class="pie-segment fiber-segment" />
                    
                    <!-- 中心圆 -->
                    <circle cx="50" cy="50" r="30" class="pie-center" />
                  </svg>
                  </div>
                
                <!-- 营养素图例 -->
                <div class="chart-legend">
                  <div class="legend-row">
                    <div class="legend-item">
                      <span class="color-box carbs-color"></span>
                      <span class="legend-text">
                        碳水化合物 {{ monthlyData.carbohydratePct.toFixed(1) }}%
                        <span class="grams-value">({{ monthlyData.totalCarbohydrate.toFixed(1) }}g)</span>
                      </span>
                </div>
                    <div class="legend-item">
                      <span class="color-box protein-color"></span>
                      <span class="legend-text">
                        蛋白质 {{ monthlyData.proteinPct.toFixed(1) }}%
                        <span class="grams-value">({{ monthlyData.totalProtein.toFixed(1) }}g)</span>
                      </span>
              </div>
            </div>
                  <div class="legend-row">
                    <div class="legend-item">
                      <span class="color-box fat-color"></span>
                      <span class="legend-text">
                        脂肪 {{ monthlyData.fatPct.toFixed(1) }}%
                        <span class="grams-value">({{ monthlyData.totalFat.toFixed(1) }}g)</span>
                      </span>
                    </div>
                    <div class="legend-item">
                      <span class="color-box fiber-color"></span>
                      <span class="legend-text">
                        膳食纤维 {{ monthlyData.fiberPct.toFixed(1) }}%
                        <span class="grams-value">({{ monthlyData.totalFiber.toFixed(1) }}g)</span>
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 餐次分布图表 -->
            <div class="monthly-meal-distribution">
              <h3>餐次分布</h3>
              <div class="meal-distribution-chart">
                <div class="meal-type-item">
                  <div class="meal-type-bar" :style="{height: `${(monthlyData.breakfastCount / monthlyData.totalMeals * 100) || 0}%`}"></div>
                  <div class="meal-type-label">早餐</div>
                  <div class="meal-type-count">{{ monthlyData.breakfastCount || 0 }}</div>
                </div>
                <div class="meal-type-item">
                  <div class="meal-type-bar" :style="{height: `${(monthlyData.lunchCount / monthlyData.totalMeals * 100) || 0}%`}"></div>
                  <div class="meal-type-label">午餐</div>
                  <div class="meal-type-count">{{ monthlyData.lunchCount || 0 }}</div>
                </div>
                <div class="meal-type-item">
                  <div class="meal-type-bar" :style="{height: `${(monthlyData.dinnerCount / monthlyData.totalMeals * 100) || 0}%`}"></div>
                  <div class="meal-type-label">晚餐</div>
                  <div class="meal-type-count">{{ monthlyData.dinnerCount || 0 }}</div>
                </div>
                <div class="meal-type-item">
                  <div class="meal-type-bar" :style="{height: `${(monthlyData.snackMorningCount / monthlyData.totalMeals * 100) || 0}%`}"></div>
                  <div class="meal-type-label">上午加餐</div>
                  <div class="meal-type-count">{{ monthlyData.snackMorningCount || 0 }}</div>
                </div>
                <div class="meal-type-item">
                  <div class="meal-type-bar" :style="{height: `${(monthlyData.snackAfternoonCount / monthlyData.totalMeals * 100) || 0}%`}"></div>
                  <div class="meal-type-label">下午加餐</div>
                  <div class="meal-type-count">{{ monthlyData.snackAfternoonCount || 0 }}</div>
                </div>
                <div class="meal-type-item">
                  <div class="meal-type-bar" :style="{height: `${(monthlyData.snackEveningCount / monthlyData.totalMeals * 100) || 0}%`}"></div>
                  <div class="meal-type-label">夜宵</div>
                  <div class="meal-type-count">{{ monthlyData.snackEveningCount || 0 }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 月度饮食评价 -->
        <div class="monthly-evaluation">
          <h3>月度饮食评价</h3>
          <div v-if="monthlyAdvice.loading" class="loading-advice">
            <i class="el-icon-loading"></i>
            <span>正在获取专业建议...</span>
          </div>
          <div v-else-if="monthlyAdvice.content" class="monthly-advice-content">
            <div class="formatted-advice" v-html="formatAdvice(monthlyAdvice.content)"></div>
          </div>
          <div v-else>
          <el-rate v-model="monthlyData.rating" disabled show-score text-color="#ff9a9e"></el-rate>
          <div class="evaluation-text">{{ monthlyData.evaluationText }}</div>
          
          <h3>改进建议</h3>
          <div class="improvement-suggestions">
            <div class="improvement-item" v-for="(improvement, index) in monthlyData.improvements" :key="index">
              <div class="improvement-number">{{index + 1}}</div>
              <div class="improvement-content">{{ improvement }}</div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分析结果对话框 -->
    <el-dialog title="饮食分析结果" :visible.sync="analysisVisible" width="80%" class="analysis-dialog">
      <div v-if="isAnalyzing" class="analysis-loading">
        <el-progress type="circle" :percentage="analysisProgress" :status="analysisProgress === 100 ? 'success' : ''"></el-progress>
        <p>{{ analysisStatus }}</p>
      </div>
      
      <div v-else class="analysis-result">
        <div class="result-header">
          <h2>饮食结构分析报告</h2>
          <p>基于您的饮食记录，我们为您提供以下营养分析和建议</p>
        </div>
        
        <!-- 营养摄入分析 -->
        <el-card class="nutrition-analysis">
          <div slot="header">
            <span>营养摄入分析</span>
          </div>
          
          <!-- 添加营养素总摄入量汇总 -->
          <div class="nutrition-summary">
            <div class="summary-item">
              <div class="summary-value">{{ nutritionData.calories.toFixed(0) }}</div>
              <div class="summary-label">总热量 (千卡)</div>
            </div>
            <div class="summary-item">
              <div class="summary-value">{{ nutritionData.carbsGrams.toFixed(1) }}</div>
              <div class="summary-label">碳水化合物 (g)</div>
            </div>
            <div class="summary-item">
              <div class="summary-value">{{ nutritionData.proteinGrams.toFixed(1) }}</div>
              <div class="summary-label">蛋白质 (g)</div>
            </div>
            <div class="summary-item">
              <div class="summary-value">{{ nutritionData.fatGrams.toFixed(1) }}</div>
              <div class="summary-label">脂肪 (g)</div>
            </div>
            <div class="summary-item">
              <div class="summary-value">{{ nutritionData.fiberGrams.toFixed(1) }}</div>
              <div class="summary-label">膳食纤维 (g)</div>
            </div>
          </div>
          
          <div class="charts-container">
            <div class="chart-item">
              <h3>主要营养素比例</h3>
              <div class="chart-placeholder">
                <!-- 重新设计饼图 -->
                <div class="pie-chart-container">
                  <div class="pie-chart">
                    <!-- 使用SVG绘制饼图 -->
                    <svg viewBox="0 0 100 100" class="pie-svg">
                      <!-- 碳水化合物扇区 -->
                      <path v-if="nutritionData.carbs > 0"
                        :d="calculatePieSegment(0, nutritionData.carbs)"
                        class="pie-segment carbs-segment" />
                      
                      <!-- 蛋白质扇区 -->
                      <path v-if="nutritionData.protein > 0"
                        :d="calculatePieSegment(nutritionData.carbs, nutritionData.carbs + nutritionData.protein)"
                        class="pie-segment protein-segment" />
                      
                      <!-- 脂肪扇区 -->
                      <path v-if="nutritionData.fat > 0"
                        :d="calculatePieSegment(nutritionData.carbs + nutritionData.protein, nutritionData.carbs + nutritionData.protein + nutritionData.fat)"
                        class="pie-segment fat-segment" />
                      
                      <!-- 膳食纤维扇区 -->
                      <path v-if="nutritionData.fiber > 0"
                        :d="calculatePieSegment(nutritionData.carbs + nutritionData.protein + nutritionData.fat, 100)"
                        class="pie-segment fiber-segment" />
                      
                      <!-- 中心圆 -->
                      <circle cx="50" cy="50" r="30" class="pie-center" />
                    </svg>
                </div>
                <div class="chart-legend">
                    <div class="legend-row">
                      <div class="legend-item">
                        <span class="color-box carbs-color"></span>
                        <span class="legend-text">
                          碳水化合物 {{ nutritionData.carbs.toFixed(1) }}%
                          <span class="grams-value">({{ nutritionData.carbsGrams.toFixed(1) }}g)</span>
                        </span>
                      </div>
                      <div class="legend-item">
                        <span class="color-box protein-color"></span>
                        <span class="legend-text">
                          蛋白质 {{ nutritionData.protein.toFixed(1) }}%
                          <span class="grams-value">({{ nutritionData.proteinGrams.toFixed(1) }}g)</span>
                        </span>
                      </div>
                    </div>
                    <div class="legend-row">
                      <div class="legend-item">
                        <span class="color-box fat-color"></span>
                        <span class="legend-text">
                          脂肪 {{ nutritionData.fat.toFixed(1) }}%
                          <span class="grams-value">({{ nutritionData.fatGrams.toFixed(1) }}g)</span>
                        </span>
                      </div>
                      <div class="legend-item">
                        <span class="color-box fiber-color"></span>
                        <span class="legend-text">
                          膳食纤维 {{ nutritionData.fiber.toFixed(1) }}%
                          <span class="grams-value">({{ nutritionData.fiberGrams.toFixed(1) }}g)</span>
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="chart-item">
              <h3>每日能量摄入</h3>
              <div class="chart-placeholder">
                <!-- 实际项目中这里应该是echarts图表 -->
                <div class="bar-chart-placeholder">
                  <div class="bar-container">
                    <div class="bar-item" :style="{ height: `${Math.min(nutritionData.calories / 20, 100)}%` }">
                      <div class="bar-value">{{ nutritionData.calories.toFixed(0) }}千卡</div>
                    </div>
                    <div class="bar-item reference" style="height: 90%;">
                      <div class="bar-value">2000千卡</div>
                    </div>
                  </div>
                  <div class="bar-labels">
                    <div>实际摄入</div>
                    <div>建议摄入</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
        
        <!-- 日膳食建议（新增） -->
        <el-card class="daily-advice" v-loading="dailyAdvice.loading">
          <div slot="header">
            <span>今日膳食专业建议</span>
          </div>
          
          <div class="daily-advice-content" v-if="dailyAdvice.content">
            <div class="formatted-advice" v-html="formatAdvice(dailyAdvice.content)"></div>
          </div>
          
          <div class="no-advice" v-else-if="!dailyAdvice.loading">
            <i class="el-icon-info"></i>
            <span>暂无今日膳食专业建议，请确保您已记录今日饮食</span>
          </div>
        </el-card>
        
        <!-- 食材建议 -->
        <el-card class="food-recommendations">
          <div slot="header">
            <span>推荐食材</span>
          </div>
          
          <div class="food-recommendations-content">
            <div class="food-category-section" v-for="(category, index) in recommendedFoods" :key="index">
              <h4>{{ category.category }}</h4>
              <div class="food-tags">
                <el-tag v-for="(food, foodIndex) in category.foods" :key="foodIndex" class="food-tag">
                  {{ food }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="analysisVisible = false">关闭</el-button>
        <el-button type="primary" @click="saveAnalysis">保存分析结果</el-button>
      </span>
    </el-dialog>

    <!-- 日膳食建议对话框 -->
    <el-dialog title="今日膳食专业建议" :visible.sync="dailyAdviceVisible" width="70%" class="advice-dialog">
      <div v-loading="dailyAdvice.loading" class="daily-advice-dialog-content">
        <div v-if="dailyAdvice.content" class="day-advice-content">
          <div class="formatted-advice" v-html="formatAdvice(dailyAdvice.content)"></div>
        </div>
        
        <div class="no-advice" v-else-if="!dailyAdvice.loading">
          <i class="el-icon-info"></i>
          <span>暂无今日膳食专业建议，请确保您已记录今日饮食</span>
        </div>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="dailyAdviceVisible = false">关闭</el-button>
        <el-button type="primary" @click="printDailyAdvice">打印建议</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'DietView',
  data() {
    return {
      currentDate: new Date().toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
      }),
      timeRange: 'day', // 'day', 'week', 'month'
      selectedWeek: null, // 不再需要默认值，因为我们直接使用当前日期
      selectedMonth: null, // 不再需要默认值，因为我们直接使用当前日期
      weeklyDateRange: '',
      monthlyDateRange: this.getMonthDateRange(new Date()),
      meals: [],
      mealTypes: [
        { value: 'breakfast', label: '早餐' },
        { value: 'lunch', label: '午餐' },
        { value: 'dinner', label: '晚餐' },
        { value: 'snack_morning', label: '上午加餐' },
        { value: 'snack_afternoon', label: '下午加餐' },
        { value: 'snack_evening', label: '夜宵' }
      ],
      foodCategories: [
        { value: 'grains', label: '谷物类' },
        { value: 'vegetables', label: '蔬菜类' },
        { value: 'fruits', label: '水果类' },
        { value: 'proteins', label: '蛋白质类' },
        { value: 'dairy', label: '奶制品' },
        { value: 'fats', label: '油脂类' },
        { value: 'nuts', label: '坚果类' },
        { value: 'others', label: '其他' }
      ],
      foodOptions: {
        grains: [
          { value: 'rice', label: '米饭' },
          { value: 'noodles', label: '面条' },
          { value: 'bread', label: '面包' },
          { value: 'oats', label: '燕麦' },
          { value: 'corn', label: '玉米' },
          { value: 'quinoa', label: '藜麦' },
          { value: 'brown_rice', label: '糙米' },
          { value: 'barley', label: '大麦' },
          { value: 'millet', label: '小米' },
          { value: 'wheat_bun', label: '馒头' },
          { value: 'dumpling', label: '饺子' },
          { value: 'whole_wheat_bread', label: '全麦面包' },
          { value: 'potato', label: '土豆' },
          { value: 'sweet_potato', label: '红薯' }
        ],
        vegetables: [
          { value: 'spinach', label: '菠菜' },
          { value: 'tomato', label: '番茄' },
          { value: 'cucumber', label: '黄瓜' },
          { value: 'carrot', label: '胡萝卜' },
          { value: 'broccoli', label: '西兰花' },
          { value: 'cabbage', label: '卷心菜' },
          { value: 'lettuce', label: '生菜' },
          { value: 'eggplant', label: '茄子' },
          { value: 'bell_pepper', label: '彩椒' },
          { value: 'onion', label: '洋葱' },
          { value: 'garlic', label: '大蒜' },
          { value: 'mushroom', label: '蘑菇' },
          { value: 'celery', label: '芹菜' },
          { value: 'green_beans', label: '四季豆' },
          { value: 'peas', label: '豌豆' },
          { value: 'pumpkin', label: '南瓜' },
          { value: 'zucchini', label: '西葫芦' },
          { value: 'radish', label: '萝卜' },
          { value: 'bok_choy', label: '青菜' },
          { value: 'kale', label: '羽衣甘蓝' },
          { value: 'cauliflower', label: '花菜' },
          { value: 'asparagus', label: '芦笋' },
          { value: 'lotus_root', label: '莲藕' },
          { value: 'bamboo_shoot', label: '竹笋' }
        ],
        fruits: [
          { value: 'apple', label: '苹果' },
          { value: 'banana', label: '香蕉' },
          { value: 'orange', label: '橙子' },
          { value: 'pear', label: '梨' },
          { value: 'grape', label: '葡萄' },
          { value: 'watermelon', label: '西瓜' },
          { value: 'strawberry', label: '草莓' },
          { value: 'blueberry', label: '蓝莓' },
          { value: 'kiwi', label: '猕猴桃' },
          { value: 'peach', label: '桃子' },
          { value: 'mango', label: '芒果' },
          { value: 'pineapple', label: '菠萝' },
          { value: 'cherry', label: '樱桃' },
          { value: 'lemon', label: '柠檬' },
          { value: 'grapefruit', label: '西柚' },
          { value: 'avocado', label: '牛油果' },
          { value: 'pomegranate', label: '石榴' },
          { value: 'durian', label: '榴莲' },
          { value: 'lychee', label: '荔枝' },
          { value: 'longan', label: '龙眼' },
          { value: 'persimmon', label: '柿子' },
          { value: 'plum', label: '李子' },
          { value: 'apricot', label: '杏' }
        ],
        proteins: [
          { value: 'chicken', label: '鸡肉' },
          { value: 'beef', label: '牛肉' },
          { value: 'pork', label: '猪肉' },
          { value: 'fish', label: '鱼' },
          { value: 'egg', label: '鸡蛋' },
          { value: 'tofu', label: '豆腐' },
          { value: 'lamb', label: '羊肉' },
          { value: 'duck', label: '鸭肉' },
          { value: 'shrimp', label: '虾' },
          { value: 'crab', label: '蟹' },
          { value: 'salmon', label: '三文鱼' },
          { value: 'tuna', label: '金枪鱼' },
          { value: 'sausage', label: '香肠' },
          { value: 'ham', label: '火腿' },
          { value: 'bacon', label: '培根' },
          { value: 'bean_curd', label: '豆干' },
          { value: 'tempeh', label: '豆豉' },
          { value: 'edamame', label: '毛豆' },
          { value: 'lentils', label: '小扁豆' },
          { value: 'black_beans', label: '黑豆' },
          { value: 'kidney_beans', label: '红豆' },
          { value: 'scallop', label: '扇贝' },
          { value: 'oyster', label: '牡蛎' },
          { value: 'quail_egg', label: '鹌鹑蛋' }
        ],
        dairy: [
          { value: 'milk', label: '牛奶' },
          { value: 'yogurt', label: '酸奶' },
          { value: 'cheese', label: '奶酪' },
          { value: 'butter', label: '黄油' },
          { value: 'cream', label: '奶油' },
          { value: 'ice_cream', label: '冰淇淋' },
          { value: 'goat_milk', label: '羊奶' },
          { value: 'soy_milk', label: '豆浆' },
          { value: 'almond_milk', label: '杏仁奶' },
          { value: 'oat_milk', label: '燕麦奶' },
          { value: 'coconut_milk', label: '椰奶' },
          { value: 'cottage_cheese', label: '农家奶酪' },
          { value: 'mozzarella', label: '马苏里拉奶酪' },
          { value: 'cheddar', label: '切达奶酪' }
        ],
        fats: [
          { value: 'olive_oil', label: '橄榄油' },
          { value: 'butter', label: '黄油' },
          { value: 'vegetable_oil', label: '植物油' },
          { value: 'sesame_oil', label: '芝麻油' },
          { value: 'coconut_oil', label: '椰子油' },
          { value: 'lard', label: '猪油' },
          { value: 'avocado_oil', label: '牛油果油' },
          { value: 'peanut_oil', label: '花生油' },
          { value: 'sunflower_oil', label: '葵花籽油' },
          { value: 'canola_oil', label: '菜籽油' },
          { value: 'ghee', label: '酥油' }
        ],
        nuts: [
          { value: 'almonds', label: '杏仁' },
          { value: 'walnuts', label: '核桃' },
          { value: 'peanuts', label: '花生' },
          { value: 'cashews', label: '腰果' },
          { value: 'pistachios', label: '开心果' },
          { value: 'hazelnuts', label: '榛子' },
          { value: 'chestnuts', label: '栗子' },
          { value: 'pine_nuts', label: '松子' },
          { value: 'pecans', label: '山核桃' },
          { value: 'macadamia', label: '夏威夷果' },
          { value: 'brazil_nuts', label: '巴西坚果' },
          { value: 'sunflower_seeds', label: '葵花籽' },
          { value: 'pumpkin_seeds', label: '南瓜籽' },
          { value: 'sesame_seeds', label: '芝麻' },
          { value: 'flax_seeds', label: '亚麻籽' },
          { value: 'chia_seeds', label: '奇亚籽' }
        ],
        others: [
          { value: 'chocolate', label: '巧克力' },
          { value: 'honey', label: '蜂蜜' },
          { value: 'sugar', label: '糖' },
          { value: 'snacks', label: '零食' },
          { value: 'soy_sauce', label: '酱油' },
          { value: 'vinegar', label: '醋' },
          { value: 'salt', label: '盐' },
          { value: 'pepper', label: '胡椒' },
          { value: 'ketchup', label: '番茄酱' },
          { value: 'mayonnaise', label: '蛋黄酱' },
          { value: 'mustard', label: '芥末' },
          { value: 'jam', label: '果酱' },
          { value: 'syrup', label: '糖浆' },
          { value: 'wine', label: '葡萄酒' },
          { value: 'beer', label: '啤酒' },
          { value: 'coffee', label: '咖啡' },
          { value: 'tea', label: '茶' },
          { value: 'juice', label: '果汁' },
          { value: 'soda', label: '碳酸饮料' },
          { value: 'cake', label: '蛋糕' },
          { value: 'cookie', label: '饼干' },
          { value: 'candy', label: '糖果' },
          { value: 'chips', label: '薯片' },
          { value: 'ice_cream', label: '冰淇淋' }
        ]
      },
      analysisVisible: false,
      isAnalyzing: false,
      analysisProgress: 0,
      analysisStatus: '正在分析您的饮食结构...',
      nutritionData: {
        calories: 0,
        carbs: 0,
        protein: 0,
        fat: 0,
        fiber: 0,
        // 添加具体的营养素值（克）
        carbsGrams: 0,
        proteinGrams: 0,
        fatGrams: 0,
        fiberGrams: 0
      },
      dietSuggestions: [
        {
          icon: 'el-icon-star-on',
          title: '摄入更多蔬菜水果',
          content: '您的蔬菜和水果摄入低于建议水平。尝试在每餐中加入至少一份蔬菜，每天吃2-3份水果。'
        },
        {
          icon: 'el-icon-warning',
          title: '减少精制碳水化合物',
          content: '您的精制碳水化合物摄入较高。建议用全谷物替代精制谷物，如选择全麦面包代替白面包。'
        },
        {
          icon: 'el-icon-s-opportunity',
          title: '适当增加优质蛋白质',
          content: '您的蛋白质摄入略低。考虑增加鱼类、豆类、坚果等优质蛋白质来源。'
        }
      ],
      recommendedFoods: [
        {
          category: '建议增加',
          foods: ['西兰花', '菠菜', '鳄梨', '三文鱼', '糙米', '藜麦', '坚果']
        },
        {
          category: '建议减少',
          foods: ['白面包', '蛋糕', '油炸食品', '加工肉类', '含糖饮料']
        }
      ],
      // 周数据
      weeklyData: {
        totalMeals: 0,
        averageCalories: 0,
        vegetableMeals: 0,
        totalCalories: 0,
        breakfastCount: 0,
        lunchCount: 0,
        dinnerCount: 0,
        snackMorningCount: 0,
        snackAfternoonCount: 0,
        snackEveningCount: 0,
        // 营养素数据
        totalCarbohydrate: 0,
        totalProtein: 0,
        totalFat: 0,
        totalFiber: 0,
        carbohydratePct: 0,
        proteinPct: 0,
        fatPct: 0,
        fiberPct: 0,
        suggestions: [
          {
            icon: 'el-icon-star-on',
            title: '保持蔬果摄入',
            content: '您本周的蔬果摄入良好，请继续保持每天至少5份蔬果的摄入量。'
          },
          {
            icon: 'el-icon-s-opportunity',
            title: '增加全谷物食物',
            content: '建议增加全谷物食品的比例，如燕麦、糙米、藜麦等，每天至少一份。'
          },
          {
            icon: 'el-icon-warning',
            title: '减少周末高热量食物',
            content: '数据显示您在周末的热量摄入明显增加，建议周末也要保持健康饮食习惯。'
          }
        ]
      },
      // 月数据
      monthlyData: {
        totalMeals: 0,
        averageCalories: 0,
        vegetableMeals: 0,
        totalCalories: 0,
        breakfastCount: 0,
        lunchCount: 0,
        dinnerCount: 0,
        snackMorningCount: 0,
        snackAfternoonCount: 0,
        snackEveningCount: 0,
        // 营养素数据
        totalCarbohydrate: 0,
        totalProtein: 0,
        totalFat: 0,
        totalFiber: 0,
        carbohydratePct: 0,
        proteinPct: 0,
        fatPct: 0,
        fiberPct: 0,
        rating: 3.7,
        evaluationText: '您的月度饮食整体表现良好，但仍有改进空间。早餐次数略少，可能存在间断性断食的情况。蛋白质和维生素摄入平衡，但脂肪摄入略高，纤维素摄入不足。',
        improvements: [
          '增加早餐次数，尽量做到每天都吃早餐，避免空腹时间过长',
          '增加膳食纤维的摄入，每天可以多吃一些全谷物、豆类和坚果',
          '减少精制碳水化合物和饱和脂肪的摄入，选择更多的不饱和脂肪如橄榄油、坚果',
          '保持足够的水分摄入，每天至少8杯水'
        ]
      },
      // 添加当前日期的格式化字符串，用于API请求
      formattedDate: '',
      isLoading: false,
      // 添加一个用于显示的日期
      displayDate: '',
      // 添加一个标记，用于区分已保存的餐次和新添加的餐次
      savedMeals: [], // 存储已保存餐次的信息，包含mealTime
      
      // 添加日膳食建议数据
      dailyAdvice: {
        content: '',
        points: [],
        loading: false
      },
      dailyAdviceVisible: false,
      weeklyAdvice: {
        intro: '',
        content: '',
        points: [],
        footer: '',
        loading: false
      },
      monthlyAdvice: {
        intro: '',
        content: '',
        points: [],
        footer: '',
        loading: false
      },
    };
  },
  computed: {
    canAnalyze() {
      // 至少有一餐且每餐至少有一种食材
      return this.meals.length > 0 && this.meals.every(meal => 
        meal.foods.length > 0 && meal.foods.every(food => 
          food.category && food.name && food.amount
        )
      );
    }
  },
  mounted() {
    // 格式化当前日期为 YYYY-MM-DD 格式
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    this.formattedDate = `${year}-${month}-${day}`;
    
    // 设置显示日期
    this.updateDisplayDate();
    
    // 初始化添加一个默认的早餐
    this.addMeal();
    
    // 获取当日饮食记录
    this.fetchTodayMeals();
    
    // 预加载周数据，以便用户切换到周视图时能立即看到数据
    this.fetchWeeklyData();
    
    // 预加载月数据，以便用户切换到月视图时能立即看到数据
    this.fetchMonthlyData();
  },
  methods: {
    // 切换时间范围
    changeTimeRange(range) {
      if (range === 'week') {
        this.fetchWeeklyData();
      } else if (range === 'month') {
        this.fetchMonthlyData();
      } else if (range === 'day') {
        // 当切换回日视图时，重新获取当日数据
        this.fetchTodayMeals();
      }
    },
    
    // 获取周日期范围 - 修改为从当前日期往前七天
    getWeekDateRange(date) {
      const end = new Date(date);
      const start = new Date(date);
      start.setDate(start.getDate() - 6); // 从当前日期往前推6天，总共7天
      
      return `${start.toLocaleDateString('zh-CN', {month: 'short', day: 'numeric'})} - ${end.toLocaleDateString('zh-CN', {month: 'short', day: 'numeric'})}`;
    },
    
    // 获取月日期范围
    getMonthDateRange(date) {
      const year = date.getFullYear();
      const month = date.getMonth();
      
      return new Date(year, month).toLocaleDateString('zh-CN', {year: 'numeric', month: 'long'});
    },
    
    // 获取周数据 - 修改为使用当前日期
    fetchWeeklyData() {
      this.isLoading = true;
      
      // 使用当前日期
      const today = new Date();
      
      // 格式化当前日期为 YYYY-MM-DD
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0');
      const date = String(today.getDate()).padStart(2, '0');
      const formattedDate = `${year}-${month}-${date}`;
      
      // 设置日期范围显示
      this.weeklyDateRange = this.getWeekDateRange(today);
      
      console.log('获取周数据，结束日期:', formattedDate);
      
      // 调用API获取周数据
      this.axios.get('/api/user/meal/week', {
        params: {
          date: formattedDate
        }
      })
      .then(response => {
        console.log('周数据API返回:', response.data);
        
        if (response.data && response.data.success && Array.isArray(response.data.data) && response.data.data.length > 0) {
          const weekData = response.data.data[0];
          
          // 更新周数据
        this.weeklyData = {
            ...this.weeklyData, // 保留建议等其他数据
            totalMeals: weekData.totalMeals || 0,
            averageCalories: parseFloat(weekData.averageCalories) || 0,
            vegetableMeals: weekData.vegetableMeals || 0,
            totalCalories: weekData.totalCalories || 0,
            breakfastCount: weekData.breakfastCount || 0,
            lunchCount: weekData.lunchCount || 0,
            dinnerCount: weekData.dinnerCount || 0,
            snackMorningCount: weekData.snackMorningCount || 0,
            snackAfternoonCount: weekData.snackAfternoonCount || 0,
            snackEveningCount: weekData.snackEveningCount || 0,
            // 营养素数据
            totalCarbohydrate: parseFloat(weekData.totalCarbohydrate) || 0,
            totalProtein: parseFloat(weekData.totalProtein) || 0,
            totalFat: parseFloat(weekData.totalFat) || 0,
            totalFiber: parseFloat(weekData.totalFiber) || 0,
            carbohydratePct: parseFloat(weekData.carbohydratePct) || 0,
            proteinPct: parseFloat(weekData.proteinPct) || 0,
            fatPct: parseFloat(weekData.fatPct) || 0,
            fiberPct: parseFloat(weekData.fiberPct) || 0
          };
          
          // 获取周建议
          this.fetchWeeklyAdvice(formattedDate);
          
          this.$message({
            message: '周数据加载成功',
            type: 'success'
          });
        } else {
          this.$message({
            message: '未找到周数据',
            type: 'warning'
          });
        }
      })
      .catch(error => {
        console.error('获取周数据失败:', error);
        this.$message({
          message: '获取周数据失败，请稍后重试',
          type: 'error'
        });
      })
      .finally(() => {
        this.isLoading = false;
      });
    },
    
    // 生成周饮食建议
    generateWeeklySuggestions() {
      // 清空现有建议
      const suggestions = [];
      
      // 根据餐次分布生成建议
      if (this.weeklyData.totalMeals > 0) {
        // 检查早餐
        if (this.weeklyData.breakfastCount < 3) {
          suggestions.push({
            icon: 'el-icon-warning',
            title: '增加早餐次数',
            content: `本周您只吃了${this.weeklyData.breakfastCount}次早餐，建议每天都吃早餐，为身体提供充足的能量开始新的一天。`
          });
        } else if (this.weeklyData.breakfastCount >= 6) {
          suggestions.push({
            icon: 'el-icon-star-on',
            title: '早餐习惯良好',
            content: '您有规律的早餐习惯值得表扬，请继续保持！'
          });
        }
        
        // 检查加餐情况
        const snackTotal = this.weeklyData.snackMorningCount + this.weeklyData.snackAfternoonCount + this.weeklyData.snackEveningCount;
        if (snackTotal > 7) {
          suggestions.push({
            icon: 'el-icon-warning',
            title: '减少加餐次数',
            content: `本周您有${snackTotal}次加餐，过多的加餐可能导致热量摄入过多，建议控制加餐次数和分量。`
          });
        }
        
        // 检查夜宵
        if (this.weeklyData.snackEveningCount > 2) {
          suggestions.push({
            icon: 'el-icon-warning',
            title: '减少夜宵',
            content: `本周您吃了${this.weeklyData.snackEveningCount}次夜宵，睡前进食可能影响睡眠质量和消化系统，建议减少夜宵次数。`
          });
        }
      }
      
      // 根据营养素分布生成建议
      // 碳水化合物建议
      if (this.weeklyData.carbohydratePct < 40) {
        suggestions.push({
          icon: 'el-icon-s-opportunity',
          title: '增加碳水化合物摄入',
          content: `您的碳水化合物摄入较低（${this.weeklyData.carbohydratePct.toFixed(1)}%），建议适当增加全谷物、薯类等优质碳水化合物食物。`
        });
      } else if (this.weeklyData.carbohydratePct > 65) {
        suggestions.push({
          icon: 'el-icon-warning',
          title: '减少碳水化合物摄入',
          content: `您的碳水化合物摄入偏高（${this.weeklyData.carbohydratePct.toFixed(1)}%），建议减少精制碳水化合物，如白面包、白米饭等。`
        });
      }
      
      // 蛋白质建议
      if (this.weeklyData.proteinPct < 10) {
        suggestions.push({
          icon: 'el-icon-s-opportunity',
          title: '增加蛋白质摄入',
          content: `您的蛋白质摄入不足（${this.weeklyData.proteinPct.toFixed(1)}%），建议增加鱼类、禽肉、豆制品等优质蛋白质来源。`
        });
      } else if (this.weeklyData.proteinPct > 35) {
        suggestions.push({
          icon: 'el-icon-warning',
          title: '减少蛋白质摄入',
          content: `您的蛋白质摄入偏高（${this.weeklyData.proteinPct.toFixed(1)}%），长期过量摄入可能增加肾脏负担。`
        });
      }
      
      // 脂肪建议
      if (this.weeklyData.fatPct < 20) {
        suggestions.push({
          icon: 'el-icon-s-opportunity',
          title: '适当增加健康脂肪',
          content: `您的脂肪摄入较低（${this.weeklyData.fatPct.toFixed(1)}%），可以适当增加坚果、橄榄油等健康脂肪来源。`
        });
      } else if (this.weeklyData.fatPct > 35) {
        suggestions.push({
          icon: 'el-icon-warning',
          title: '减少脂肪摄入',
          content: `您的脂肪摄入偏高（${this.weeklyData.fatPct.toFixed(1)}%），建议减少油炸食品、高脂肪肉类等食物的摄入。`
        });
      }
      
      // 纤维素建议
      if (this.weeklyData.fiberPct < 5) {
        suggestions.push({
          icon: 'el-icon-s-opportunity',
          title: '增加膳食纤维摄入',
          content: `您的膳食纤维摄入不足（${this.weeklyData.fiberPct.toFixed(1)}%），建议增加蔬菜、水果、全谷物等食物的摄入。`
        });
      }
      
      // 热量建议
      if (this.weeklyData.averageCalories < 1200) {
        suggestions.push({
          icon: 'el-icon-warning',
          title: '热量摄入不足',
          content: `您的平均热量摄入仅为${this.weeklyData.averageCalories.toFixed(0)}千卡/天，可能无法满足基本代谢需求，建议适当增加食物摄入量。`
        });
      } else if (this.weeklyData.averageCalories > 2500) {
        suggestions.push({
          icon: 'el-icon-warning',
          title: '注意控制热量',
          content: `您的平均热量摄入为${this.weeklyData.averageCalories.toFixed(0)}千卡/天，建议控制总热量摄入，避免能量过剩。`
        });
      }
      
      // 蔬果餐次建议
      if (this.weeklyData.vegetableMeals < 5) {
        suggestions.push({
          icon: 'el-icon-s-opportunity',
          title: '增加蔬果摄入',
          content: `本周您只有${this.weeklyData.vegetableMeals}餐包含蔬果，建议每天摄入足够的蔬菜水果，提供维生素、矿物质和膳食纤维。`
        });
      } else if (this.weeklyData.vegetableMeals >= 10) {
        suggestions.push({
          icon: 'el-icon-star-on',
          title: '蔬果摄入充足',
          content: '您的蔬果摄入量充足，这对维持健康的饮食结构非常重要，请继续保持！'
        });
      }
      
      // 如果没有生成任何建议，添加一个默认建议
      if (suggestions.length === 0) {
        suggestions.push({
          icon: 'el-icon-star-on',
          title: '饮食结构良好',
          content: '您的周饮食结构相对均衡，请继续保持健康的饮食习惯。'
        });
      }
      
      // 限制最多显示3条建议
      this.weeklyData.suggestions = suggestions.slice(0, 3);
    },
    
    // 获取月数据 - 始终使用当前月份
    fetchMonthlyData() {
      // 始终使用当前月份
      const today = new Date();
      this.isLoading = true;
      
      // 格式化当前月份为YYYY-MM-DD，使用该月的第一天
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0');
      const formattedDate = `${year}-${month}-01`;
      
      // 设置月份范围显示
      this.monthlyDateRange = this.getMonthDateRange(today);
      
      console.log('获取月数据，日期:', formattedDate);
      
      // 调用API获取月数据
      this.axios.get('/api/user/meal/month', {
        params: {
          date: formattedDate
        }
      })
      .then(response => {
        console.log('月数据API返回:', response.data);
        
        if (response.data && response.data.success && Array.isArray(response.data.data) && response.data.data.length > 0) {
          const monthData = response.data.data[0];
          
          // 更新月数据
        this.monthlyData = {
            ...this.monthlyData, // 保留评价和建议等其他数据
            totalMeals: monthData.totalMeals || 0,
            averageCalories: parseFloat(monthData.averageCalories) || 0,
            vegetableMeals: monthData.vegetableMeals || 0,
            totalCalories: monthData.totalCalories || 0,
            breakfastCount: monthData.breakfastCount || 0,
            lunchCount: monthData.lunchCount || 0,
            dinnerCount: monthData.dinnerCount || 0,
            snackMorningCount: monthData.snackMorningCount || 0,
            snackAfternoonCount: monthData.snackAfternoonCount || 0,
            snackEveningCount: monthData.snackEveningCount || 0,
            // 营养素数据
            totalCarbohydrate: parseFloat(monthData.totalCarbohydrate) || 0,
            totalProtein: parseFloat(monthData.totalProtein) || 0,
            totalFat: parseFloat(monthData.totalFat) || 0,
            totalFiber: parseFloat(monthData.totalFiber) || 0,
            carbohydratePct: parseFloat(monthData.carbohydratePct) || 0,
            proteinPct: parseFloat(monthData.proteinPct) || 0,
            fatPct: parseFloat(monthData.fatPct) || 0,
            fiberPct: parseFloat(monthData.fiberPct) || 0
          };
          
          // 获取月度建议
          this.fetchMonthlyAdvice(formattedDate);
          
          this.$message({
            message: '月数据加载成功',
            type: 'success'
          });
        } else {
          this.$message({
            message: '未找到月数据',
            type: 'warning'
          });
        }
      })
      .catch(error => {
        console.error('获取月数据失败:', error);
        this.$message({
          message: '获取月数据失败，请稍后重试',
          type: 'error'
        });
      })
      .finally(() => {
        this.isLoading = false;
      });
    },
    
    // 生成月度饮食评价 - 修改为使用当前月份
    generateMonthlyEvaluation() {
      // 根据营养素分布和餐次情况评分
      let rating = 3.0; // 基础评分
      
      // 评估早餐次数
      const today = new Date();
      const daysInMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0).getDate();
      const breakfastRatio = this.monthlyData.breakfastCount / daysInMonth;
      
      if (breakfastRatio >= 0.9) {
        rating += 0.5; // 几乎每天都吃早餐
      } else if (breakfastRatio >= 0.7) {
        rating += 0.3; // 大多数天吃早餐
      } else if (breakfastRatio < 0.5) {
        rating -= 0.3; // 早餐次数不足
      }
      
      // 评估营养素平衡
      if (this.monthlyData.carbohydratePct >= 45 && this.monthlyData.carbohydratePct <= 65) {
        rating += 0.3; // 碳水比例适中
      } else {
        rating -= 0.2; // 碳水比例不佳
      }
      
      if (this.monthlyData.proteinPct >= 15 && this.monthlyData.proteinPct <= 25) {
        rating += 0.3; // 蛋白质比例适中
      } else if (this.monthlyData.proteinPct > 25) {
        rating += 0.1; // 蛋白质偏高但可接受
      } else {
        rating -= 0.2; // 蛋白质不足
      }
      
      if (this.monthlyData.fatPct >= 20 && this.monthlyData.fatPct <= 30) {
        rating += 0.3; // 脂肪比例适中
      } else {
        rating -= 0.2; // 脂肪比例不佳
      }
      
      // 评估蔬果摄入
      if (this.monthlyData.vegetableMeals / this.monthlyData.totalMeals >= 0.7) {
        rating += 0.5; // 蔬果摄入充足
      } else if (this.monthlyData.vegetableMeals / this.monthlyData.totalMeals >= 0.5) {
        rating += 0.2; // 蔬果摄入一般
      } else {
        rating -= 0.3; // 蔬果摄入不足
      }
      
      // 限制评分范围在1-5之间
      this.monthlyData.rating = Math.max(1, Math.min(5, rating));
      
      // 生成评价文本
      let evaluationText = '您的月度饮食';
      
      if (rating >= 4.5) {
        evaluationText += '表现非常优秀！饮食结构均衡，营养素摄入合理，餐次规律。';
      } else if (rating >= 4) {
        evaluationText += '表现良好。饮食结构基本均衡，营养素摄入较为合理。';
      } else if (rating >= 3) {
        evaluationText += '整体表现一般，有一些需要改进的地方。';
      } else {
        evaluationText += '需要较多改进，目前的饮食结构不够均衡。';
      }
      
      // 添加具体评价
      if (breakfastRatio < 0.7) {
        evaluationText += '早餐次数不足，可能影响上午的能量供应和代谢水平。';
      }
      
      if (this.monthlyData.carbohydratePct < 45) {
        evaluationText += '碳水化合物摄入偏低，可能导致能量不足。';
      } else if (this.monthlyData.carbohydratePct > 65) {
        evaluationText += '碳水化合物摄入偏高，注意控制精制碳水的摄入。';
      }
      
      if (this.monthlyData.proteinPct < 15) {
        evaluationText += '蛋白质摄入不足，可能影响肌肉维持和修复。';
      } else if (this.monthlyData.proteinPct > 30) {
        evaluationText += '蛋白质摄入过高，长期可能增加肾脏负担。';
      }
      
      if (this.monthlyData.fatPct < 20) {
        evaluationText += '脂肪摄入偏低，可能影响脂溶性维生素的吸收。';
      } else if (this.monthlyData.fatPct > 35) {
        evaluationText += '脂肪摄入偏高，注意控制饱和脂肪的摄入。';
      }
      
      if (this.monthlyData.fiberPct < 5) {
        evaluationText += '膳食纤维摄入不足，可能影响肠道健康。';
      }
      
      this.monthlyData.evaluationText = evaluationText;
      
      // 生成改进建议
      const improvements = [];
      
      if (breakfastRatio < 0.7) {
        improvements.push('增加早餐次数，尽量做到每天都吃早餐，避免空腹时间过长');
      }
      
      if (this.monthlyData.carbohydratePct < 45) {
        improvements.push('适当增加优质碳水化合物的摄入，如全谷物、薯类等');
      } else if (this.monthlyData.carbohydratePct > 65) {
        improvements.push('减少精制碳水化合物的摄入，选择全谷物食品替代精制谷物');
      }
      
      if (this.monthlyData.proteinPct < 15) {
        improvements.push('增加优质蛋白质的摄入，如瘦肉、鱼类、蛋类、豆制品等');
      } else if (this.monthlyData.proteinPct > 30) {
        improvements.push('适当减少蛋白质的摄入，保持在适宜范围内');
      }
      
      if (this.monthlyData.fatPct < 20) {
        improvements.push('适当增加健康脂肪的摄入，如坚果、橄榄油、鱼油等');
      } else if (this.monthlyData.fatPct > 35) {
        improvements.push('减少脂肪特别是饱和脂肪的摄入，少吃油炸食品和高脂肪肉类');
      }
      
      if (this.monthlyData.fiberPct < 5) {
        improvements.push('增加膳食纤维的摄入，多吃蔬菜、水果、全谷物、豆类和坚果');
      }
      
      if (this.monthlyData.vegetableMeals / this.monthlyData.totalMeals < 0.5) {
        improvements.push('增加蔬果摄入量，每天应至少摄入5份蔬菜水果');
      }
      
      // 如果没有具体建议，添加一个通用建议
      if (improvements.length === 0) {
        improvements.push('继续保持当前的良好饮食习惯，定期监测身体状况');
      }
      
      // 添加一条关于水分摄入的通用建议
      improvements.push('保持充足的水分摄入，每天至少8杯水，避免含糖饮料');
      
      // 限制最多显示4条建议
      this.monthlyData.improvements = improvements.slice(0, 4);
    },
    
    // 添加获取月建议的方法
    fetchMonthlyAdvice(date) {
      this.monthlyAdvice.loading = true;
      
      this.axios.get('/api/api/advice/month', {
        params: {
          date: date
        }
      })
      .then(response => {
        console.log('月建议API返回:', response.data);
        
        if (response.data) {
          // 处理返回的文本内容
          const adviceText = response.data;
          
          // 存储完整内容
          this.monthlyAdvice.content = adviceText;
        }
      })
      .catch(error => {
        console.error('获取月建议失败:', error);
        // 失败时使用默认的评价
        this.generateMonthlyEvaluation();
      })
      .finally(() => {
        this.monthlyAdvice.loading = false;
      });
    },
    
    // 添加一个新餐次
    addMeal() {
      const currentTime = new Date();
      // 根据当前时间推断餐次类型
      let mealType = 'breakfast';
      const hours = currentTime.getHours();
      
      if (hours >= 5 && hours < 10) {
        mealType = 'breakfast';
      } else if (hours >= 10 && hours < 12) {
        mealType = 'snack_morning';
      } else if (hours >= 12 && hours < 14) {
        mealType = 'lunch';
      } else if (hours >= 14 && hours < 17) {
        mealType = 'snack_afternoon';
      } else if (hours >= 17 && hours < 20) {
        mealType = 'dinner';
      } else {
        mealType = 'snack_evening';
      }
      
      this.meals.push({
        type: mealType,
        time: currentTime,
        foods: [],
        isSaved: false // 标记为新添加的餐次
      });
      
      // 默认添加一种食材
      this.addFood(this.meals.length - 1);
    },
    
    // 删除餐次
    removeMeal(index) {
      const meal = this.meals[index];
      
      // 如果是已保存的餐次，需要调用API删除
      if (meal.isSaved) {
        this.$confirm('确定要删除这个餐次吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteSavedMeal(index);
        }).catch(() => {
          // 取消删除
        });
      } else {
        // 如果是新添加的餐次，直接从数组中删除
      this.meals.splice(index, 1);
      }
    },
    
    // 删除已保存的餐次
    deleteSavedMeal(index) {
      const meal = this.meals[index];
      
      if (!meal || !meal.isSaved || !meal.originalMealTime) {
        this.$message.error('无法删除，餐次信息不完整');
        return;
      }
      
      this.isLoading = true;
      
      // 调用删除API
      this.axios.delete('/api/user/meal/delete', {
        params: {
          date: this.formattedDate,
          mealTime: meal.originalMealTime
        }
      })
      .then(response => {
        if (response.data && response.data.success) {
          this.$message({
            message: '餐次删除成功',
            type: 'success'
          });
          
          // 从meals数组中删除
          this.meals.splice(index, 1);
          
          // 从savedMeals数组中删除
          const savedIndex = this.savedMeals.findIndex(saved => 
            saved.date === this.formattedDate && saved.mealTime === meal.originalMealTime
          );
          if (savedIndex !== -1) {
            this.savedMeals.splice(savedIndex, 1);
          }
          
          // 如果没有餐次了，添加一个空的
          if (this.meals.length === 0) {
            this.addMeal();
          }
        } else {
          this.$message.error(response.data.message || '删除失败');
        }
      })
      .catch(error => {
        console.error('删除餐次失败:', error);
        this.$message.error('删除餐次失败，请稍后重试');
      })
      .finally(() => {
        this.isLoading = false;
      });
    },
    
    // 添加食材
    addFood(mealIndex) {
      if (!this.meals[mealIndex]) return;
      
      this.meals[mealIndex].foods.push({
        category: '',
        name: '',
        amount: 100 // 默认100克
      });
    },
    
    // 删除食材
    removeFood(mealIndex, foodIndex) {
      if (!this.meals[mealIndex] || !this.meals[mealIndex].foods[foodIndex]) return;
      
      // 如果是已保存的餐次，不允许删除单个食材
      if (this.meals[mealIndex].isSaved) {
        this.$message({
          message: '已保存的餐次不能删除单个食材，只能删除整个餐次',
          type: 'warning'
        });
        return;
      }
      
      // 如果是新添加的餐次，可以删除单个食材
      this.meals[mealIndex].foods.splice(foodIndex, 1);
    },
    
    // 食材类别变更时，清空食材名称
    onFoodCategoryChange(mealIndex, foodIndex) {
      if (!this.meals[mealIndex] || !this.meals[mealIndex].foods[foodIndex]) return;
      
      this.meals[mealIndex].foods[foodIndex].name = '';
    },
    
    // 获取特定类别的食材选项
    getFoodOptions(category) {
      return category ? this.foodOptions[category] || [] : [];
    },
    
    // 分析饮食结构 - 修改为同时获取日膳食建议
    analyzeDiet() {
      this.analysisVisible = true;
      this.isAnalyzing = true;
      this.analysisProgress = 0;
      
      // 获取营养百分比数据
      this.axios.get('/api/user/meal/nutritionPercentages/daily', {
        params: {
          date: this.formattedDate
        }
      })
      .then(response => {
        console.log('获取营养数据成功:', response.data);
        
        if (response.data && response.data.success && response.data.data) {
          const nutritionData = response.data.data;
          
          // 更新营养数据
          this.nutritionData = {
            ...this.nutritionData, // 保留之前计算的克数值
            calories: nutritionData.totalCalories || 0,
            carbs: nutritionData.carbohydratePct || 0,
            protein: nutritionData.proteinPct || 0,
            fat: nutritionData.fatPct || 0,
            fiber: nutritionData.fiberPct || 0
          };
          
          console.log('更新后的营养数据:', this.nutritionData);
          
          // 获取日膳食建议
          this.fetchDailyAdvice();
        } else {
          console.log('营养数据格式不正确或为空');
        }
      })
      .catch(error => {
        console.error('获取营养数据失败:', error);
        this.$message({
          message: '获取营养数据失败，将使用默认数据',
          type: 'warning'
        });
      });
      
      // 模拟分析进度
      const interval = setInterval(() => {
        this.analysisProgress += 10;
        
        if (this.analysisProgress === 30) {
          this.analysisStatus = '正在计算营养素摄入...';
        } else if (this.analysisProgress === 60) {
          this.analysisStatus = '正在生成饮食建议...';
        } else if (this.analysisProgress === 90) {
          this.analysisStatus = '正在完成分析报告...';
        }
        
        if (this.analysisProgress >= 100) {
          clearInterval(interval);
          this.analysisProgress = 100;
          setTimeout(() => {
            this.isAnalyzing = false;
            
            // 根据营养数据生成饮食建议
            this.generateDietSuggestions();
          }, 500);
        }
      }, 300);
    },
    
    // 根据营养数据生成饮食建议
    generateDietSuggestions() {
      // 清空现有建议
      this.dietSuggestions = [];
      
      // 碳水化合物建议
      if (this.nutritionData.carbs < 40) {
        this.dietSuggestions.push({
          icon: 'el-icon-s-opportunity',
          title: '增加碳水化合物摄入',
          content: '您的碳水化合物摄入较低（' + this.nutritionData.carbs.toFixed(1) + '%），建议适当增加全谷物、薯类等优质碳水化合物食物。'
        });
      } else if (this.nutritionData.carbs > 65) {
        this.dietSuggestions.push({
          icon: 'el-icon-warning',
          title: '减少碳水化合物摄入',
          content: '您的碳水化合物摄入偏高（' + this.nutritionData.carbs.toFixed(1) + '%），建议减少精制碳水化合物，如白面包、白米饭等。'
        });
      }
      
      // 蛋白质建议
      if (this.nutritionData.protein < 10) {
        this.dietSuggestions.push({
          icon: 'el-icon-s-opportunity',
          title: '增加蛋白质摄入',
          content: '您的蛋白质摄入不足（' + this.nutritionData.protein.toFixed(1) + '%），建议增加鱼类、禽肉、豆制品等优质蛋白质来源。'
        });
      } else if (this.nutritionData.protein > 35) {
        this.dietSuggestions.push({
          icon: 'el-icon-warning',
          title: '减少蛋白质摄入',
          content: '您的蛋白质摄入偏高（' + this.nutritionData.protein.toFixed(1) + '%），长期过量摄入可能增加肾脏负担。'
        });
      }
      
      // 脂肪建议
      if (this.nutritionData.fat < 20) {
        this.dietSuggestions.push({
          icon: 'el-icon-s-opportunity',
          title: '适当增加健康脂肪',
          content: '您的脂肪摄入较低（' + this.nutritionData.fat.toFixed(1) + '%），可以适当增加坚果、橄榄油等健康脂肪来源。'
        });
      } else if (this.nutritionData.fat > 35) {
        this.dietSuggestions.push({
          icon: 'el-icon-warning',
          title: '减少脂肪摄入',
          content: '您的脂肪摄入偏高（' + this.nutritionData.fat.toFixed(1) + '%），建议减少油炸食品、高脂肪肉类等食物的摄入。'
        });
      }
      
      // 纤维素建议
      if (this.nutritionData.fiber < 5) {
        this.dietSuggestions.push({
          icon: 'el-icon-s-opportunity',
          title: '增加膳食纤维摄入',
          content: '您的膳食纤维摄入不足（' + this.nutritionData.fiber.toFixed(1) + '%），建议增加蔬菜、水果、全谷物等食物的摄入。'
        });
      }
      
      // 热量建议
      if (this.nutritionData.calories < 1200) {
        this.dietSuggestions.push({
          icon: 'el-icon-warning',
          title: '热量摄入不足',
          content: '您的热量摄入仅为' + this.nutritionData.calories.toFixed(0) + '千卡，可能无法满足基本代谢需求，建议适当增加食物摄入量。'
        });
      } else if (this.nutritionData.calories > 2500) {
        this.dietSuggestions.push({
          icon: 'el-icon-warning',
          title: '注意控制热量',
          content: '您的热量摄入为' + this.nutritionData.calories.toFixed(0) + '千卡，建议控制总热量摄入，避免能量过剩。'
        });
      }
      
      // 如果没有生成任何建议，添加一个默认建议
      if (this.dietSuggestions.length === 0) {
        this.dietSuggestions.push({
          icon: 'el-icon-star-on',
          title: '饮食结构良好',
          content: '您的饮食结构相对均衡，请继续保持健康的饮食习惯。'
        });
      }
      
      // 更新推荐食材
      this.updateRecommendedFoods();
    },
    
    // 更新推荐食材
    updateRecommendedFoods() {
      // 根据营养数据推荐食材
      const increaseList = [];
      const decreaseList = [];
      
      // 根据碳水比例推荐
      if (this.nutritionData.carbs < 40) {
        increaseList.push('全麦面包', '糙米', '燕麦', '红薯', '藜麦');
      } else if (this.nutritionData.carbs > 65) {
        decreaseList.push('白面包', '白米饭', '精制面条', '蛋糕', '饼干');
      }
      
      // 根据蛋白质比例推荐
      if (this.nutritionData.protein < 10) {
        increaseList.push('鸡胸肉', '鱼肉', '豆腐', '鸡蛋', '酸奶');
      } else if (this.nutritionData.protein > 35) {
        decreaseList.push('红肉', '加工肉制品', '高蛋白补充剂');
      }
      
      // 根据脂肪比例推荐
      if (this.nutritionData.fat < 20) {
        increaseList.push('橄榄油', '坚果', '牛油果', '三文鱼');
      } else if (this.nutritionData.fat > 35) {
        decreaseList.push('油炸食品', '奶油', '肥肉', '黄油', '加工零食');
      }
      
      // 根据纤维素比例推荐
      if (this.nutritionData.fiber < 5) {
        increaseList.push('西兰花', '菠菜', '豆类', '全谷物', '水果');
      }
      
      // 更新推荐食材列表
      this.recommendedFoods = [
        {
          category: '建议增加',
          foods: [...new Set(increaseList)]
        },
        {
          category: '建议减少',
          foods: [...new Set(decreaseList)]
        }
      ];
    },
    
    // 保存饮食记录
    saveMealRecord() {
      if (this.meals.length === 0) {
        this.$message({
          message: '没有饮食记录可保存',
          type: 'warning'
        });
        return;
      }
      
      // 筛选出未保存的餐次
      const unsavedMeals = this.meals.filter(meal => !meal.isSaved);
      
      if (unsavedMeals.length === 0) {
        this.$message({
          message: '没有新的饮食记录需要保存',
          type: 'info'
        });
        return;
      }
      
      // 显示加载状态
      this.isLoading = true;
      
      // 格式化当前日期为 YYYY-MM-DD 格式 - 使用当前日期而不是测试日期
      const formattedDate = this.formattedDate;
      
      // 准备请求数据，只处理未保存的餐次
      const mealRecords = unsavedMeals.map(meal => {
        // 格式化时间为 HH:MM:SS 格式
        const mealTime = meal.time;
        const hours = String(mealTime.getHours()).padStart(2, '0');
        const minutes = String(mealTime.getMinutes()).padStart(2, '0');
        const seconds = '00'; // 默认秒数为00
        const formattedTime = `${hours}:${minutes}:${seconds}`;
        
        // 获取餐次类型的英文
        const mealTypeMap = {
          'breakfast': 'Breakfast',
          'lunch': 'Lunch',
          'dinner': 'Dinner',
          'snack_morning': 'MorningSnack',
          'snack_afternoon': 'AfternoonSnack',
          'snack_evening': 'EveningSnack'
        };
        
        // 格式化食物数据
        const formattedFoods = meal.foods.map(food => {
          // 食物类别映射
          const categoryMap = {
            'grains': 'Grain',
            'vegetables': 'Vegetable',
            'fruits': 'Fruit',
            'proteins': 'Protein',
            'dairy': 'Dairy',
            'fats': 'Fat',
            'nuts': 'Nut',
            'others': 'Other'
          };
          
          // 获取食物的标签
          let foodLabel = food.name;
          const foodOption = this.foodOptions[food.category]?.find(option => option.value === food.name);
          if (foodOption) {
            foodLabel = foodOption.label;
          }
          
          return {
            category: categoryMap[food.category] || food.category,
            name: foodLabel,
            amount: food.amount
          };
        });
        
        return {
          mealDate: formattedDate,
          mealTime: formattedTime,
          mealType: mealTypeMap[meal.type] || meal.type,
          foods: formattedFoods
        };
      });
      
      // 发送请求保存每一餐
      const savePromises = mealRecords.map(record => {
        return this.axios.post('/api/user/meal/add', record);
      });
      
      Promise.all(savePromises)
        .then(responses => {
          // 检查所有响应是否都成功
          const allSuccess = responses.every(response => 
            response.data && response.data.success === true
          );
          
          if (allSuccess) {
            this.$message({
              message: '饮食记录保存成功',
              type: 'success'
            });
            // 重新获取当日数据以确保显示最新状态
            this.fetchTodayMeals();
          } else {
            // 找出失败的响应
            const failedResponses = responses.filter(response => 
              !response.data || response.data.success !== true
            );
            
            // 获取第一个错误消息
            const errorMessage = failedResponses.length > 0 && 
              failedResponses[0].data && 
              failedResponses[0].data.message ? 
              failedResponses[0].data.message : '保存饮食记录失败';
            
            console.error('保存饮食记录失败:', failedResponses);
            this.$message({
              message: errorMessage,
              type: 'error'
            });
          }
        })
        .catch(error => {
          console.error('保存饮食记录失败:', error);
          this.$message({
            message: '保存饮食记录失败，请稍后重试',
            type: 'error'
          });
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    
    // 保存分析结果
    saveAnalysis() {
      this.$message({
        message: '分析结果已保存',
        type: 'success'
      });
      this.analysisVisible = false;
    },
    
    // 重置表单
    resetForm() {
      this.$confirm('确定要重置所有饮食记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.meals = [];
        this.addMeal(); // 添加一个默认的餐次
        this.$message({
          type: 'success',
          message: '重置成功'
        });
      }).catch(() => {
        // 取消重置
      });
    },
    
    // 获取当日饮食记录
    fetchTodayMeals() {
      this.isLoading = true;
      
      console.log('正在获取日期为', this.formattedDate, '的饮食记录');
      
      this.axios.get('/api/user/meal/day', {
        params: {
          date: this.formattedDate
        }
      })
      .then(response => {
        // 调试输出
        console.log('API返回数据:', response.data);
        
        // 检查API返回的数据结构
        if (response.data && response.data.success && Array.isArray(response.data.data) && response.data.data.length > 0) {
          console.log('找到', response.data.data.length, '条饮食记录');
          
          // 清空默认添加的餐次
          this.meals = [];
          // 清空已保存的餐次记录
          this.savedMeals = [];
          
          // 计算营养素总量
          let totalCarbs = 0;
          let totalProtein = 0;
          let totalFat = 0;
          let totalFiber = 0;
          let totalCalories = 0;
          
          // 将后端数据转换为前端数据格式
          response.data.data.forEach((meal, index) => {
            console.log(`处理第${index+1}条记录:`, meal);
            
            // 累加营养素值
            totalCarbs += parseFloat(meal.carbohydrate) || 0;
            totalProtein += parseFloat(meal.protein) || 0;
            totalFat += parseFloat(meal.fat) || 0;
            totalFiber += parseFloat(meal.fiber) || 0;
            totalCalories += parseFloat(meal.calories) || 0;
            
            // 转换餐次类型
            const mealTypeMap = {
              'Breakfast': 'breakfast',
              'Lunch': 'lunch',
              'Dinner': 'dinner',
              'MorningSnack': 'snack_morning',
              'AfternoonSnack': 'snack_afternoon',
              'EveningSnack': 'snack_evening'
            };
            
            // 解析时间
            const timeParts = meal.mealTime.split(':');
            const mealTime = new Date();
            mealTime.setHours(parseInt(timeParts[0]));
            mealTime.setMinutes(parseInt(timeParts[1]));
            mealTime.setSeconds(parseInt(timeParts[2]));
            
            // 转换食物类别
            const categoryMap = {
              'Grain': 'grains',
              'Vegetable': 'vegetables',
              'Fruit': 'fruits',
              'Protein': 'proteins',
              'Dairy': 'dairy',
              'Fat': 'fats',
              'Nut': 'nuts',
              'Other': 'others'
            };
            
            // 转换食物数据
            const foods = meal.foods.map(food => {
              const category = categoryMap[food.category] || 'others';
              const name = this.findFoodValueByName(category, food.name);
              
              return {
                category: category,
                name: name,
                amount: food.amount
              };
            });
            
            // 添加到meals数组
            this.meals.push({
              type: mealTypeMap[meal.mealType] || 'breakfast',
              time: mealTime,
              foods: foods,
              isSaved: true, // 标记为已保存的餐次
              originalMealTime: meal.mealTime // 保存原始的mealTime用于删除操作
            });
            
            // 记录已保存的餐次信息
            this.savedMeals.push({
              date: meal.mealDate,
              mealTime: meal.mealTime
            });
          });
          
          console.log('营养素总量计算完成:', {
            carbs: totalCarbs,
            protein: totalProtein,
            fat: totalFat,
            fiber: totalFiber,
            calories: totalCalories
          });
          
          // 存储营养素具体值（克）
          this.nutritionData.carbsGrams = totalCarbs;
          this.nutritionData.proteinGrams = totalProtein;
          this.nutritionData.fatGrams = totalFat;
          this.nutritionData.fiberGrams = totalFiber;
          
          this.$message({
            message: '已加载今日饮食记录',
            type: 'success'
          });
        } else {
          console.log('没有找到饮食记录或数据格式不正确');
          // 如果没有记录，显示一个空的餐次
          if (this.meals.length === 0) {
            this.addMeal();
          }
        }
      })
      .catch(error => {
        console.error('获取今日饮食记录失败:', error);
        this.$message({
          message: '获取今日饮食记录失败，显示默认内容',
          type: 'warning'
        });
        
        // 确保至少有一个空的餐次
        if (this.meals.length === 0) {
          this.addMeal();
        }
      })
      .finally(() => {
        this.isLoading = false;
      });
    },
    
    // 根据食物名称查找对应的值
    findFoodValueByName(category, foodName) {
      console.log(`尝试匹配食物: 类别=${category}, 名称=${foodName}`);
      
      // 如果类别不存在，返回空字符串
      if (!this.foodOptions[category]) {
        console.log(`类别 ${category} 不存在`);
        return foodName; // 返回原始名称
      }
      
      // 先尝试精确匹配
      const exactMatch = this.foodOptions[category].find(item => 
        item.label === foodName || item.value === foodName
      );
      
      if (exactMatch) {
        console.log(`找到精确匹配: ${exactMatch.value}`);
        return exactMatch.value;
      }
      
      // 特殊处理一些常见的拼写错误或变体
      const specialCases = {
        'Brocooli': 'broccoli',  // 示例中的拼写错误
        'apple': 'apple',        // 小写转换
        'grape': 'grape',        // 小写转换
        'Chicken Breast': 'chicken' // 部分匹配
      };
      
      if (specialCases[foodName]) {
        const specialValue = specialCases[foodName];
        console.log(`应用特殊匹配规则: ${foodName} -> ${specialValue}`);
        
        // 检查特殊值是否存在于选项中
        const specialMatch = this.foodOptions[category].find(item => 
          item.value === specialValue
        );
        
        if (specialMatch) {
          return specialMatch.value;
        }
      }
      
      // 如果没有精确匹配，尝试不区分大小写的匹配
      const lowerCaseName = foodName.toLowerCase();
      const caseInsensitiveMatch = this.foodOptions[category].find(item => 
        item.label.toLowerCase() === lowerCaseName || 
        item.value.toLowerCase() === lowerCaseName
      );
      
      if (caseInsensitiveMatch) {
        console.log(`找到不区分大小写匹配: ${caseInsensitiveMatch.value}`);
        return caseInsensitiveMatch.value;
      }
      
      // 如果仍然没有匹配，尝试模糊匹配（包含关系）
      const fuzzyMatch = this.foodOptions[category].find(item => 
        item.label.toLowerCase().includes(lowerCaseName) || 
        lowerCaseName.includes(item.label.toLowerCase()) ||
        item.value.toLowerCase().includes(lowerCaseName) || 
        lowerCaseName.includes(item.value.toLowerCase())
      );
      
      if (fuzzyMatch) {
        console.log(`找到模糊匹配: ${fuzzyMatch.value}`);
        return fuzzyMatch.value;
      }
      
      // 如果都没匹配到，返回原始名称
      console.log(`没有找到匹配，使用原始名称: ${foodName}`);
      return foodName;
    },
    // 更新显示日期
    updateDisplayDate() {
      // 解析日期字符串为Date对象
      const dateParts = this.formattedDate.split('-');
      const dateObj = new Date(
        parseInt(dateParts[0]),
        parseInt(dateParts[1]) - 1,
        parseInt(dateParts[2])
      );
      
      // 格式化为友好的显示格式
      this.displayDate = dateObj.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
      });
    },
    
    // 刷新数据
    refreshData() {
      this.fetchTodayMeals();
    },
    
    // 计算饼图扇区路径
    calculatePieSegment(startPercent, endPercent) {
      // 确保百分比在0-100之间
      startPercent = Math.max(0, Math.min(100, startPercent));
      endPercent = Math.max(0, Math.min(100, endPercent));
      
      // 如果起始和结束百分比相同，则不绘制
      if (startPercent === endPercent) {
        return '';
      }
      
      // 转换为角度（0-360度）
      const startAngle = (startPercent / 100) * 360;
      const endAngle = (endPercent / 100) * 360;
      
      // 计算起点和终点坐标
      const startX = 50 + 50 * Math.cos(this.degreesToRadians(startAngle - 90));
      const startY = 50 + 50 * Math.sin(this.degreesToRadians(startAngle - 90));
      const endX = 50 + 50 * Math.cos(this.degreesToRadians(endAngle - 90));
      const endY = 50 + 50 * Math.sin(this.degreesToRadians(endAngle - 90));
      
      // 确定是否为大弧（大于180度）
      const largeArcFlag = endAngle - startAngle > 180 ? 1 : 0;
      
      // 构建SVG路径
      return `M 50 50 L ${startX} ${startY} A 50 50 0 ${largeArcFlag} 1 ${endX} ${endY} Z`;
    },
    
    // 角度转弧度
    degreesToRadians(degrees) {
      return degrees * Math.PI / 180;
    },
    
    // 获取日膳食建议
    fetchDailyAdvice() {
      this.dailyAdvice.loading = true;
      
      this.axios.get(`/api/api/advice/day`, {
        params: {
          date: this.formattedDate
        }
      })
      .then(response => {
        console.log('获取日膳食建议成功:', response.data);
        
        if (response.data) {
          // 处理返回的文本内容
          const adviceText = response.data;
          
          // 存储完整内容
          this.dailyAdvice.content = adviceText;
        }
      })
      .catch(error => {
        console.error('获取日膳食建议失败:', error);
        this.$message({
          message: '获取日膳食建议失败，请稍后重试',
          type: 'error'
        });
      })
      .finally(() => {
        this.dailyAdvice.loading = false;
      });
    },
    
    // 显示日膳食建议对话框
    showDailyAdvice() {
      this.dailyAdviceVisible = true;
      
      // 如果还没有获取过建议，则获取
      if (!this.dailyAdvice.content && !this.dailyAdvice.loading) {
        this.fetchDailyAdvice();
      }
    },
    
    // 打印日膳食建议
    printDailyAdvice() {
      const formattedAdvice = this.formatAdvice(this.dailyAdvice.content);
      const printWindow = window.open('', '_blank');
      
      printWindow.document.write(`
        <html>
          <head>
            <title>今日膳食专业建议</title>
            <style>
              body {
                font-family: Arial, sans-serif;
                line-height: 1.6;
                color: #333;
                max-width: 800px;
                margin: 0 auto;
                padding: 20px;
                text-align: left;
              }
              h1 {
                text-align: left;
                color: #67C23A;
                margin-bottom: 30px;
              }
              .print-date {
                text-align: left;
                font-size: 14px;
                color: #909399;
                margin-bottom: 20px;
              }
              .print-footer {
                text-align: left;
                margin-top: 40px;
                font-size: 12px;
                color: #909399;
                border-top: 1px solid #EBEEF5;
                padding-top: 20px;
              }
              /* 章节标题样式 */
              .advice-section-title {
                font-size: 20px;
                color: #ff9a9e;
                margin: 25px 0 15px 0;
                padding-bottom: 10px;
                border-bottom: 1px solid #ffecd2;
                display: flex;
                align-items: center;
              }
              .advice-section-title:first-child {
                margin-top: 0;
              }
              .section-number {
                margin-right: 8px;
                color: #ff9a9e;
                font-weight: bold;
              }
              /* 列表项样式 */
              .advice-item-number {
                margin: 12px 0;
                display: flex;
                align-items: flex-start;
              }
              .advice-item-number .number {
                font-weight: bold;
                color: #ff9a9e;
                margin-right: 8px;
                flex-shrink: 0;
                min-width: 20px;
              }
              .advice-item-number .content {
                flex: 1;
              }
              .advice-item-dash {
                margin: 8px 0 8px 20px;
                display: flex;
                align-items: flex-start;
              }
              .advice-item-dash i {
                color: #67C23A;
                margin-right: 8px;
                flex-shrink: 0;
              }
              .advice-item-dash .content {
                flex: 1;
              }
              .advice-item-arrow {
                margin: 12px 0;
                display: flex;
                align-items: flex-start;
              }
              .advice-item-arrow i {
                color: #E6A23C;
                margin-right: 8px;
                flex-shrink: 0;
              }
              .advice-item-arrow .content {
                flex: 1;
              }
              .advice-item-indented {
                margin: 8px 0 8px 30px;
                display: flex;
                align-items: flex-start;
              }
              .advice-item-indented i {
                color: #F56C6C;
                margin-right: 8px;
                flex-shrink: 0;
              }
              .advice-item-indented .content {
                flex: 1;
              }
              .date-range {
                background-color: #f0f9eb;
                color: #67C23A;
                padding: 2px 6px;
                border-radius: 4px;
                font-weight: bold;
              }
              strong {
                color: #E6A23C;
                font-weight: bold;
              }
              .advice-icon {
                font-size: 18px;
                vertical-align: middle;
                margin: 0 4px;
              }
              .advice-icon.success {
                color: #67C23A;
              }
            </style>
          </head>
          <body>
            <h1>今日膳食专业建议</h1>
            <div class="print-date">日期：${this.displayDate}</div>
            <div class="formatted-advice">
              ${formattedAdvice}
            </div>
            <div class="print-footer">
              此建议由 HealthyLife 系统生成，仅供参考，不构成医疗建议
            </div>
          </body>
        </html>
      `);
      
      printWindow.document.close();
      printWindow.focus();
      
      setTimeout(() => {
        printWindow.print();
      }, 500);
    },
    // 添加获取周建议的方法
    fetchWeeklyAdvice(date) {
      this.weeklyAdvice.loading = true;
      
      this.axios.get('/api/api/advice/week', {
        params: {
          date: date
        }
      })
      .then(response => {
        console.log('周建议API返回:', response.data);
        
        if (response.data) {
          // 存储完整内容
          this.weeklyAdvice.content = response.data;
        }
      })
      .catch(error => {
        console.error('获取周建议失败:', error);
        // 失败时使用默认的建议
        this.generateWeeklySuggestions();
      })
      .finally(() => {
        this.weeklyAdvice.loading = false;
      });
    },
    
    // 格式化建议显示
    formatAdvice(text) {
      if (!text) return '';
      
      // 1. 先规范化中文字符的序号格式
      // 处理一、二、三这样的中文序号，统一添加样式
      text = text.replace(/^(一|二|三|四|五|六|七|八|九|十)、\s*(.*?)$/gm, 
        '<h3 class="advice-section-title chinese-number"><span class="section-number">$1、</span>$2</h3>');
      
      // 处理1、2、3这样的数字序号加顿号的标题
      text = text.replace(/^(\d+)、\s*(.*?)$/gm,
        '<h3 class="advice-section-title number-title"><span class="section-number">$1、</span>$2</h3>');
      
      // 2. 处理标题行中的特殊图标
      text = text.replace(/🔍\s*(数据分析.*?:|饮食分析:?)/g, 
        '<h3 class="advice-section-title"><i class="el-icon-data-analysis"></i> $1</h3>');
      text = text.replace(/✏️\s*(改善建议.*?:|营养建议:?)/g, 
        '<h3 class="advice-section-title"><i class="el-icon-edit-outline"></i> $1</h3>');
      
      // 3. 处理数字列表（不带顿号的常规数字列表）
      text = text.replace(/^(\d+)\.\s+(.*?)$/gm, 
        '<div class="advice-item-number"><span class="number">$1.</span> <span class="content">$2</span></div>');
      
      // 4. 处理特殊的角标列表
      text = text.replace(/^[▶▷➤➢►]\s+(.*?)$/gm, 
        '<div class="advice-item-arrow"><i class="el-icon-arrow-right"></i> <span class="content">$1</span></div>');
      
      // 5. 处理破折号列表
      text = text.replace(/^-\s+(.*?)$/gm, 
        '<div class="advice-item-dash"><i class="el-icon-minus"></i> <span class="content">$1</span></div>');
      
      // 6. 处理缩进的右箭头列表
      text = text.replace(/^\s*[>→➔]\s+(.*?)$/gm, 
        '<div class="advice-item-indented"><i class="el-icon-d-arrow-right"></i> <span class="content">$1</span></div>');
      
      // 7. 处理强调内容
      text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
      
      // 8. 处理特殊符号和标识
      text = text.replace(/🔍/g, '<i class="el-icon-search advice-icon"></i>');
      text = text.replace(/✅/g, '<i class="el-icon-check advice-icon success"></i>');
      text = text.replace(/🍽️/g, '<i class="el-icon-food advice-icon"></i>');
      text = text.replace(/📊/g, '<i class="el-icon-data-line advice-icon"></i>');
      text = text.replace(/✏️/g, '<i class="el-icon-edit advice-icon"></i>');
      
      // 9. 处理时间范围和日期
      text = text.replace(/(\d{1,2}\.\d{1,2}-\d{1,2}\.\d{1,2})/g, '<span class="date-range">$1</span>');
      
      // 10. 处理换行
      text = text.replace(/\n/g, '<br>');
      
      return text;
    },
  }
};
</script>

<style scoped>
.diet-container {
  padding: 20px;
  max-width: 100%;
  width: 100%;
  margin: 0 auto;
  background-color: #fffaf0; /* 淡黄色背景 */
  min-height: 100vh;
  height: 100%;
  box-sizing: border-box;
  background-image: linear-gradient(120deg, #ffecd2 0%, #fcb69f 100%);
  background-attachment: fixed;
  display: flex;
  flex-direction: column;
}

.page-header {
  text-align: center;
  margin-bottom: 20px;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 15px;
  border-radius: 15px;
  box-shadow: 0 6px 16px rgba(255, 182, 193, 0.2);
}

.page-header h1 {
  color: #ff9a9e; /* 粉色标题 */
  font-size: 32px;
  margin-bottom: 10px;
  text-shadow: 1px 1px 2px rgba(255, 154, 158, 0.3);
  font-weight: bold;
}

.sub-title {
  font-size: 16px;
  color: #ffa751; /* 橙黄色副标题 */
  margin: 0;
  font-weight: 500;
}

/* 时间范围选择器样式 */
.time-range-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.time-range-selector .el-radio-group {
  margin-right: 20px;
}

.date-picker-container {
  display: flex;
  align-items: center;
}

.date-label {
  margin-right: 10px;
  color: #ff9a9e;
  font-weight: 500;
}

/* 周视图和月视图样式 */
.weekly-view,
.monthly-view {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.analysis-card {
  flex: 1;
  border-radius: 12px;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 8px 20px rgba(255, 182, 193, 0.25);
  border: none;
  overflow: hidden;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
}

.weekly-summary,
.monthly-summary {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.weekly-stats,
.monthly-stats {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  background-color: #fff9f9;
  padding: 15px 25px;
  border-radius: 10px;
  min-width: 120px;
  box-shadow: 0 4px 10px rgba(255, 154, 158, 0.1);
  transition: all 0.3s;
}

.stat-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 12px rgba(255, 154, 158, 0.2);
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #ff9a9e;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #ffaa80;
}

.weekly-nutrition-chart,
.monthly-nutrition-chart {
  background-color: #fff9f9;
  padding: 20px;
  border-radius: 10px;
  margin-bottom: 20px;
  box-shadow: 0 4px 10px rgba(255, 154, 158, 0.1);
}

.weekly-nutrition-chart h3,
.monthly-nutrition-chart h3 {
  text-align: center;
  color: #ff9a9e;
  margin-bottom: 20px;
  font-weight: 600;
}

/* 周趋势图表占位样式 */
.line-chart-placeholder {
  height: 200px;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  padding: 0 10px;
}

.line-chart-day {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 40px;
}

.line-chart-bar {
  width: 30px;
  background: linear-gradient(to top, #ff9a9e, #fad0c4);
  border-radius: 4px 4px 0 0;
  transition: all 0.3s;
}

.line-chart-bar:hover {
  transform: scaleY(1.05);
  background: linear-gradient(to top, #ff9a9e, #fad0c4 70%);
  box-shadow: 0 4px 8px rgba(255, 154, 158, 0.3);
}

.line-chart-label {
  margin-top: 10px;
  font-size: 12px;
  color: #ffaa80;
}

/* 月度图表占位样式 */
.monthly-chart-placeholder {
  padding: 10px;
}

.monthly-chart-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.monthly-chart-label {
  width: 70px;
  font-size: 14px;
  color: #ffaa80;
  text-align: right;
  margin-right: 10px;
}

.monthly-chart-progress {
  flex: 1;
  height: 20px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 10px;
  overflow: hidden;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
}

.monthly-chart-bar {
  height: 100%;
  background: linear-gradient(to right, #ff9a9e, #fad0c4);
  border-radius: 10px;
  transition: width 1s ease;
}

.monthly-chart-value {
  width: 50px;
  text-align: left;
  margin-left: 10px;
  font-size: 14px;
  color: #ff9a9e;
  font-weight: 500;
}

/* 周建议和月度评价样式 */
.weekly-suggestions,
.monthly-evaluation {
  padding: 20px;
  background-color: #fff9f9;
  border-radius: 10px;
  margin: 0 20px 20px;
  box-shadow: 0 4px 10px rgba(255, 154, 158, 0.1);
}

.weekly-suggestions h3,
.monthly-evaluation h3 {
  color: #ff9a9e;
  margin-bottom: 15px;
  font-weight: 600;
  text-align: center;
}

.evaluation-text {
  color: #ffaa80;
  line-height: 1.6;
  margin: 15px 0 20px;
  padding: 10px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 8px;
  border-left: 4px solid #ff9a9e;
}

.improvement-suggestions {
  margin-top: 15px;
}

.improvement-item {
  display: flex;
  margin-bottom: 12px;
  padding: 10px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 8px;
  transition: all 0.3s;
}

.improvement-item:hover {
  transform: translateX(5px);
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 6px rgba(255, 154, 158, 0.15);
}

.improvement-number {
  width: 25px;
  height: 25px;
  background-color: #ff9a9e;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  margin-right: 10px;
  flex-shrink: 0;
}

.improvement-content {
  color: #ffaa80;
  line-height: 1.6;
}

/* 原有样式调整和保留 */
.diet-record-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.meal-card {
  margin-bottom: 20px;
  border-radius: 12px;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 8px 20px rgba(255, 182, 193, 0.25);
  border: none;
  overflow: hidden;
  flex: 1;
}

.meal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  background-color: #ffecd2;
  color: #ff9a9e;
  padding: 15px 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-date {
  font-size: 14px;
  color: #ff9a9e;
  font-weight: normal;
  margin-left: 10px;
}

.header-right {
  display: flex;
  align-items: center;
}

.add-meal-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 60px;
  margin: 15px 0;
  background-color: #fff5e6;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px dashed #ffcc99;
}

.add-meal-btn:hover {
  background-color: #ffecd2;
  transform: translateY(-3px);
}

.add-meal-btn i {
  font-size: 20px;
  margin-right: 10px;
  color: #ffaa80;
}

.meal-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ffe6e6;
  border-radius: 10px;
  background-color: #fff9f9;
  box-shadow: 0 4px 10px rgba(255, 154, 158, 0.1);
  transition: all 0.3s;
}

.saved-meal {
  border: 1px solid #e1f3d8;
  background-color: #f0f9eb;
}

.saved-tag {
  margin: 0 10px;
}

.saved-meal-tip {
  margin-top: 10px;
  padding: 8px 12px;
  background-color: #f0f9eb;
  border-radius: 4px;
  color: #67C23A;
  font-size: 12px;
  display: flex;
  align-items: center;
}

.saved-meal-tip i {
  margin-right: 5px;
  font-size: 14px;
}

.meal-item-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.meal-type-select {
  width: 130px;
  margin-right: 15px;
}

.meal-time-picker {
  width: 130px;
  margin-right: 15px;
}

.delete-meal-btn {
  margin-left: auto;
  background-color: #ffd6d6;
  border-color: #ffd6d6;
}

.delete-meal-btn:hover {
  background-color: #ffb6b6;
  border-color: #ffb6b6;
}

.food-items-container {
  padding: 15px;
  background-color: #fffbf7;
  border-radius: 8px;
  border: 1px solid #ffe6cc;
}

.food-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px;
  background-color: white;
  border-radius: 8px;
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(255, 182, 193, 0.1);
}

.food-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(255, 182, 193, 0.2);
}

.food-category {
  width: 120px;
  margin-right: 12px;
}

.food-name {
  flex: 1;
  margin-right: 12px;
}

.food-amount {
  width: 130px;
  margin-right: 5px;
}

.unit-label {
  margin-right: 10px;
  color: #ffaa80;
  font-weight: 500;
}

.delete-food-btn {
  margin-left: 5px;
  background-color: #ffe6e6;
  border-color: #ffe6e6;
  color: #ff8080;
}

.delete-food-btn:hover {
  background-color: #ffd6d6;
  border-color: #ffd6d6;
}

.add-food-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
  margin-top: 10px;
  background-color: #fff5f5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1.5px dashed #ffcccc;
}

.add-food-btn:hover {
  background-color: #ffe6e6;
}

.add-food-btn i {
  font-size: 16px;
  margin-right: 5px;
  color: #ff9a9e;
}

.action-btns {
  display: flex;
  justify-content: center;
  margin-top: 25px;
  margin-bottom: 15px;
}

.action-btns button {
  margin: 0 10px;
  padding: 12px 35px;
  border-radius: 20px;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s;
}

.action-btns .el-button--primary {
  background: linear-gradient(45deg, #ff9a9e 0%, #fad0c4 99%, #fad0c4 100%);
  border-color: #ff9a9e;
}

.action-btns .el-button--primary:hover {
  transform: translateY(-3px);
  box-shadow: 0 7px 14px rgba(255, 154, 158, 0.3);
  background: linear-gradient(45deg, #ff9a9e 0%, #fad0c4 70%, #fad0c4 100%);
}

.action-btns .el-button--success {
  background: linear-gradient(45deg, #67C23A 0%, #85CE61 99%, #85CE61 100%);
  border-color: #67C23A;
}

.action-btns .el-button--success:hover {
  transform: translateY(-3px);
  box-shadow: 0 7px 14px rgba(103, 194, 58, 0.3);
  background: linear-gradient(45deg, #67C23A 0%, #85CE61 70%, #85CE61 100%);
}

.action-btns .el-button--default {
  background: linear-gradient(45deg, #ffecd2 0%, #fcb69f 99%, #fcb69f 100%);
  border-color: #ffecd2;
  color: white;
}

.action-btns .el-button--default:hover {
  transform: translateY(-3px);
  box-shadow: 0 7px 14px rgba(252, 182, 159, 0.3);
}

/* 分析结果对话框样式 */
.analysis-dialog :deep(.el-dialog) {
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(255, 182, 193, 0.3);
}

.analysis-dialog :deep(.el-dialog__header) {
  background: linear-gradient(45deg, #ff9a9e 0%, #fad0c4 99%, #fad0c4 100%);
  padding: 20px;
}

.analysis-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

.analysis-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  background-color: #fff9f0;
  border-radius: 15px;
  box-shadow: 0 4px 12px rgba(255, 182, 193, 0.1);
}

.analysis-loading p {
  margin-top: 20px;
  font-size: 16px;
  color: #ff9a9e;
  font-weight: 500;
}

.result-header {
  text-align: center;
  margin-bottom: 30px;
  background-color: #fff9f9;
  padding: 15px;
  border-radius: 12px;
}

.result-header h2 {
  color: #ff9a9e;
  margin-bottom: 8px;
  font-weight: 600;
  text-align: center;
}

.result-header p {
  color: #ffaa80;
  text-align: center;
}

.nutrition-analysis, 
.diet-suggestions, 
.food-recommendations {
  margin-bottom: 25px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 6px 16px rgba(255, 182, 193, 0.15);
  border: none;
}

.nutrition-analysis :deep(.el-card__header),
.diet-suggestions :deep(.el-card__header),
.food-recommendations :deep(.el-card__header) {
  background-color: #ffecd2;
  padding: 15px 20px;
  color: #ff9a9e;
  font-weight: 600;
  font-size: 18px;
}

.charts-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  margin-top: 20px;
  padding: 10px;
}

.chart-item {
  width: 45%;
  min-width: 300px;
  text-align: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff9f9;
  border-radius: 10px;
  transition: all 0.3s;
}

.chart-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(255, 154, 158, 0.15);
}

.chart-item h3 {
  margin-bottom: 15px;
  color: #ff9a9e;
  font-weight: 600;
}

.chart-placeholder {
  height: 250px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 简易饼图替代 */
.pie-chart-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 100%;
}

.pie-chart {
  width: 200px;
  height: 200px;
  position: relative;
}

.pie-svg {
  width: 100%;
  height: 100%;
}

.pie-segment {
  transition: all 0.8s ease;
}

.carbs-segment {
  fill: #67C23A;
}

.protein-segment {
  fill: #E6A23C;
}

.fat-segment {
  fill: #F56C6C;
}

.fiber-segment {
  fill: #909399;
}

.pie-center {
  fill: white;
  stroke: #f5f5f5;
  stroke-width: 1;
}

/* 图例样式优化 */
.chart-legend {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
  width: 100%;
}

.legend-row {
  display: flex;
  justify-content: center;
  width: 100%;
  margin-bottom: 10px;
  max-width: 400px;
}

.legend-item {
  display: flex;
  align-items: center;
  margin: 0 5px;
  padding: 5px 10px;
  background-color: white;
  border-radius: 20px;
  box-shadow: 0 2px 6px rgba(255, 154, 158, 0.1);
  width: 180px;
  justify-content: flex-start;
}

.color-box {
  width: 16px;
  height: 16px;
  margin-right: 8px;
  border-radius: 3px;
  flex-shrink: 0;
}

.carbs-color {
  background-color: #67C23A;
}

.protein-color {
  background-color: #E6A23C;
}

.fat-color {
  background-color: #F56C6C;
}

.fiber-color {
  background-color: #909399;
}

.legend-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 14px;
}

.grams-value {
  font-size: 12px;
  color: #909399;
  margin-left: 4px;
}

/* 简易柱状图替代 */
.bar-chart-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.bar-container {
  flex: 1;
  display: flex;
  justify-content: space-around;
  align-items: flex-end;
  padding-bottom: 20px;
}

.bar-item {
  width: 80px;
  background: linear-gradient(to top, #ff9a9e, #fad0c4);
  border-radius: 8px 8px 0 0;
  position: relative;
  display: flex;
  justify-content: center;
  box-shadow: 0 4px 8px rgba(255, 154, 158, 0.2);
}

.bar-item.reference {
  background: linear-gradient(to top, #ffecd2, #fcb69f);
}

.bar-value {
  position: absolute;
  top: -25px;
  font-size: 14px;
  color: #ff9a9e;
  font-weight: 500;
  background-color: white;
  padding: 2px 8px;
  border-radius: 10px;
  box-shadow: 0 2px 6px rgba(255, 154, 158, 0.1);
}

.bar-labels {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
}

.bar-labels div {
  width: 80px;
  text-align: center;
  font-size: 14px;
  color: #ffaa80;
  font-weight: 500;
}

/* 饮食建议样式 */
.suggestion-content {
  padding: 15px;
}

.suggestion-item {
  display: flex;
  margin-bottom: 20px;
  padding: 15px;
  border-bottom: 1px solid #ffe6e6;
  background-color: #fff9f9;
  border-radius: 10px;
  transition: all 0.3s;
}

.suggestion-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(255, 154, 158, 0.15);
}

.suggestion-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.suggestion-icon {
  margin-right: 20px;
  width: 50px;
  height: 50px;
  background: linear-gradient(45deg, #ff9a9e 0%, #fad0c4 99%, #fad0c4 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  box-shadow: 0 4px 8px rgba(255, 154, 158, 0.2);
}

.suggestion-icon i {
  font-size: 24px;
  color: white;
}

.suggestion-text h4 {
  margin: 0 0 10px 0;
  color: #ff9a9e;
  font-weight: 600;
}

.suggestion-text p {
  margin: 0;
  color: #ffaa80;
  line-height: 1.6;
}

/* 食材推荐样式 */
.food-recommendations-content {
  padding: 15px;
}

.food-category-section {
  margin-bottom: 25px;
  padding: 15px;
  background-color: #fff9f9;
  border-radius: 10px;
  transition: all 0.3s;
}

.food-category-section:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(255, 154, 158, 0.15);
}

.food-category-section:last-child {
  margin-bottom: 0;
}

.food-category-section h4 {
  margin: 0 0 15px 0;
  color: #ff9a9e;
  font-weight: 600;
  padding-bottom: 8px;
  border-bottom: 2px solid #ffecd2;
}

.food-tags {
  display: flex;
  flex-wrap: wrap;
}

.food-tag {
  margin: 0 10px 10px 0;
  background-color: #ffecd2;
  border-color: #ffecd2;
  color: #ffaa80;
  font-weight: 500;
  transition: all 0.3s;
}

.food-tag:hover {
  transform: translateY(-2px);
  background-color: #ffdfb8;
  color: #ff9a9e;
}

/* 媒体查询适配小屏幕 */
@media screen and (max-width: 768px) {
  .chart-item {
    width: 100%;
  }
  
  .food-item {
    flex-wrap: wrap;
  }
  
  .food-category,
  .food-name {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .time-range-selector {
    flex-direction: column;
  }
  
  .time-range-selector .el-radio-group {
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .stat-item {
    min-width: 40%;
  }
}

/* 美化Element UI组件 */
:deep(.el-select .el-input__inner) {
  border-color: #ffd6d6;
}

:deep(.el-select .el-input__inner:focus) {
  border-color: #ff9a9e;
}

:deep(.el-input-number .el-input__inner) {
  border-color: #ffd6d6;
}

:deep(.el-input-number .el-input__inner:focus) {
  border-color: #ff9a9e;
}

:deep(.el-input-number__decrease:hover),
:deep(.el-input-number__increase:hover) {
  color: #ff9a9e;
}

:deep(.el-time-picker .el-input__inner) {
  border-color: #ffd6d6;
}

:deep(.el-time-picker .el-input__inner:focus) {
  border-color: #ff9a9e;
}

:deep(.el-progress-circle__path) {
  stroke: #ff9a9e !important;
}

:deep(.el-dialog__footer) {
  background-color: #fff9f0;
  border-top: 1px solid #ffecd2;
}

:deep(.el-button--primary) {
  background-color: #ff9a9e;
  border-color: #ff9a9e;
}

:deep(.el-button--primary:hover) {
  background-color: #ffb6b9;
  border-color: #ffb6b9;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

:deep(.el-dialog__body) {
  background-color: #fffbf7;
}

:deep(.el-radio-button__inner) {
  background-color: #fff5f5;
  border-color: #ffd6d6;
  color: #ff9a9e;
}

:deep(.el-radio-button__orig-radio:checked + .el-radio-button__inner) {
  background-color: #ff9a9e;
  border-color: #ff9a9e;
  box-shadow: -1px 0 0 0 #ff9a9e;
}

:deep(.el-date-editor) {
  width: 160px;
}

:deep(.el-date-editor .el-input__inner) {
  border-color: #ffd6d6;
}

:deep(.el-date-editor .el-input__inner:focus) {
  border-color: #ff9a9e;
}

:deep(.el-rate__icon) {
  font-size: 22px;
  margin-right: 6px;
}

:deep(.el-rate__text) {
  font-size: 16px;
  color: #ff9a9e;
}

.save-tip {
  margin: 10px 0 15px;
  border-radius: 8px;
  background-color: #f0f9eb;
  border-color: #e1f3d8;
}

.save-tip :deep(.el-alert__title) {
  color: #67C23A;
  font-size: 14px;
}

.save-tip :deep(.el-alert__icon) {
  color: #67C23A;
}

.delete-food-btn[disabled] {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
  cursor: not-allowed;
}

/* 营养素总摄入量汇总样式 */
.nutrition-summary {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  margin-bottom: 20px;
  background-color: #f8f9fa;
  border-radius: 10px;
  padding: 15px 10px;
}

.summary-item {
  text-align: center;
  padding: 10px;
  min-width: 100px;
}

.summary-value {
  font-size: 20px;
  font-weight: bold;
  color: #ff9a9e;
  margin-bottom: 5px;
}

.summary-label {
  font-size: 12px;
  color: #909399;
}

/* 餐次分布图表 */
.meal-distribution {
  background-color: #fff9f9;
  padding: 20px;
  border-radius: 10px;
  margin-bottom: 20px;
  box-shadow: 0 4px 10px rgba(255, 154, 158, 0.1);
}

.meal-distribution h3 {
  text-align: center;
  color: #ff9a9e;
  margin-bottom: 20px;
  font-weight: 600;
}

.meal-distribution-chart {
  display: flex;
  justify-content: space-around;
  align-items: flex-end;
  height: 200px;
  padding: 0 10px;
}

.meal-type-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 60px;
}

.meal-type-bar {
  width: 30px;
  background: linear-gradient(to top, #ff9a9e, #fad0c4);
  border-radius: 4px 4px 0 0;
  transition: all 0.3s;
  min-height: 5px;
}

.meal-type-bar:hover {
  transform: scaleY(1.05);
  background: linear-gradient(to top, #ff9a9e, #fad0c4 70%);
  box-shadow: 0 4px 8px rgba(255, 154, 158, 0.3);
}

.meal-type-label {
  margin-top: 10px;
  font-size: 12px;
  color: #ffaa80;
  text-align: center;
  white-space: nowrap;
}

.meal-type-count {
  font-size: 14px;
  font-weight: 600;
  color: #ff9a9e;
  margin-top: 5px;
}

/* 周营养素饼图 */
.weekly-pie-chart {
  margin-top: 20px;
}

/* 月度营养素饼图 */
.monthly-pie-chart {
  margin-top: 20px;
}

/* 月度餐次分布 */
.monthly-meal-distribution {
  margin-top: 30px;
  background-color: #fff9f9;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(255, 154, 158, 0.1);
}

.monthly-meal-distribution h3 {
  text-align: center;
  color: #ff9a9e;
  margin-bottom: 20px;
  font-weight: 600;
}

/* 日膳食建议样式 */
.daily-advice {
  margin-bottom: 25px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 6px 16px rgba(255, 182, 193, 0.15);
  border: none;
}

.daily-advice :deep(.el-card__header) {
  background-color: #f0f9eb;
  padding: 15px 20px;
  color: #67C23A;
  font-weight: 600;
  font-size: 18px;
}

.daily-advice-content {
  padding: 15px;
}

.advice-intro {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 8px;
  color: #606266;
  font-style: italic;
  line-height: 1.6;
  text-align: left;
}

.advice-points {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.advice-point {
  padding: 15px;
  background-color: #f0f9eb;
  border-radius: 10px;
  transition: all 0.3s;
  text-align: left;
}

.advice-point:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.15);
}

.advice-point-title {
  color: #67C23A;
  font-size: 16px;
  margin-bottom: 10px;
  font-weight: 500;
  text-align: left;
}

.advice-point-content {
  color: #606266;
  line-height: 1.6;
  text-align: left;
}

.advice-point-items {
  padding-left: 20px;
  margin: 10px 0;
  text-align: left;
}

.advice-point-items li {
  color: #606266;
  margin-bottom: 12px;
  line-height: 1.6;
  text-align: left;
  position: relative;
  padding-left: 5px;
}

.advice-point-items li::before {
  content: "•";
  color: #67C23A;
  font-weight: bold;
  display: inline-block;
  width: 1em;
  margin-left: -1em;
}

.no-advice {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 30px;
  color: #909399;
}

.no-advice i {
  font-size: 24px;
  margin-right: 10px;
  color: #E6A23C;
}

.no-advice span {
  text-align: left;
}

/* 日膳食建议对话框样式 */
.advice-dialog :deep(.el-dialog__header) {
  background-color: #f0f9eb;
  padding: 20px;
}

.advice-dialog :deep(.el-dialog__title) {
  color: #67C23A;
  font-weight: 600;
}

.daily-advice-dialog-content {
  padding: 20px;
  min-height: 300px;
  text-align: left;
}

.advice-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  background-color: #fff9f0;
  border-radius: 15px;
  box-shadow: 0 4px 12px rgba(255, 182, 193, 0.1);
}

.advice-loading i {
  font-size: 36px;
  color: #ff9a9e;
  margin-bottom: 20px;
}

.advice-loading span {
  font-size: 16px;
  color: #ffaa80;
  font-weight: 500;
}

.weekly-advice-content,
.monthly-advice-content {
  padding: 20px;
  background-color: #fff9f9;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(255, 154, 158, 0.1);
  line-height: 1.6;
}

.advice-intro {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 8px;
  color: #606266;
  font-style: italic;
  line-height: 1.6;
  text-align: left;
}

.advice-points {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.advice-point {
  padding: 15px;
  background-color: #f0f9eb;
  border-radius: 10px;
  transition: all 0.3s;
  text-align: left;
}

.advice-point:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.15);
}

.advice-point-title {
  color: #67C23A;
  font-size: 16px;
  margin-bottom: 10px;
  font-weight: 500;
  text-align: left;
}

.advice-point-content {
  color: #606266;
  line-height: 1.6;
  text-align: left;
}

.advice-point-items {
  padding-left: 20px;
  margin: 10px 0;
  text-align: left;
}

.advice-point-items li {
  color: #606266;
  margin-bottom: 12px;
  line-height: 1.6;
  text-align: left;
  position: relative;
  padding-left: 5px;
}

.advice-point-items li::before {
  content: "•";
  color: #67C23A;
  font-weight: bold;
  display: inline-block;
  width: 1em;
  margin-left: -1em;
}

.advice-footer {
  margin-top: 20px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 8px;
  color: #909399;
  font-size: 14px;
  text-align: left;
  font-style: italic;
}

/* 日、周、月建议样式 */
.day-advice-content,
.weekly-advice-content,
.monthly-advice-content {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  transition: all 0.3s ease;
  text-align: left;
}

.day-advice-content:hover,
.weekly-advice-content:hover,
.monthly-advice-content:hover {
  background: #ecf5ff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

/* 替换旧的pre样式，改为格式化建议的样式 */
.formatted-advice {
  font-size: 16px;
  line-height: 1.8;
  color: #606266;
  text-align: left;
}

/* 章节标题样式 */
.advice-section-title {
  font-size: 20px;
  color: #ff9a9e;
  margin: 25px 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ffecd2;
  display: flex;
  align-items: center;
}

.advice-section-title:first-child {
  margin-top: 0;
}

.advice-section-title i {
  margin-right: 8px;
  font-size: 22px;
}

/* 中文序号样式 */
.advice-section-title.chinese-number {
  color: #303133;
  font-weight: bold;
}

/* 数字序号样式 */
.advice-section-title.number-title {
  color: #303133;
  font-weight: bold;
}

.section-number {
  margin-right: 8px;
  color: #ff9a9e;
  font-weight: bold;
}

/* 列表项样式 */
.advice-item-number {
  margin: 12px 0;
  display: flex;
  align-items: flex-start;
}

.advice-item-number .number {
  font-weight: bold;
  color: #ff9a9e;
  margin-right: 8px;
  flex-shrink: 0;
  min-width: 20px;
}

.advice-item-number .content {
  flex: 1;
}

.advice-item-dash {
  margin: 8px 0 8px 20px;
  display: flex;
  align-items: flex-start;
}

.advice-item-dash i {
  color: #67C23A;
  margin-right: 8px;
  flex-shrink: 0;
}

.advice-item-dash .content {
  flex: 1;
}

/* 新增箭头列表样式 */
.advice-item-arrow {
  margin: 12px 0;
  display: flex;
  align-items: flex-start;
}

.advice-item-arrow i {
  color: #E6A23C;
  margin-right: 8px;
  flex-shrink: 0;
}

.advice-item-arrow .content {
  flex: 1;
}

/* 缩进列表样式 */
.advice-item-indented {
  margin: 8px 0 8px 30px;
  display: flex;
  align-items: flex-start;
}

.advice-item-indented i {
  color: #F56C6C;
  margin-right: 8px;
  flex-shrink: 0;
}

.advice-item-indented .content {
  flex: 1;
}

/* 日期范围 */
.date-range {
  background-color: #f0f9eb;
  color: #67C23A;
  padding: 2px 6px;
  border-radius: 4px;
  font-weight: bold;
}

.formatted-advice strong {
  color: #E6A23C;
  font-weight: bold;
}

.advice-icon {
  font-size: 18px;
  vertical-align: middle;
  margin: 0 4px;
}

.advice-icon.success {
  color: #67C23A;
}

.loading-advice {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.loading-advice i {
  font-size: 36px;
  color: #ff9a9e;
  margin-bottom: 15px;
}

.loading-advice p {
  font-size: 16px;
  color: #909399;
  margin: 0;
}
</style>

